星期四, 2月 01, 2018

以python為例,建立一個簡單的web service

希望可以達成的結果

http://localhost:8080/users
http://localhost:8080/users/{id}

1.安裝套件

ubuntu 環境

sudo easy_install web.py
windows 環境

pip.exe install web.py

2.建立一個簡單的xml,叫user_data.xml

<users>
    <user id="1" name="Rocky" age="38"/>
    <user id="2" name="Steve" age="50"/>
    <user id="3" name="Melinda" age="38"/>
</users>
3.建立一個py
import web
import xml.etree.ElementTree as ET

tree = ET.parse('user_data.xml')
root = tree.getroot()

urls = (
    '/users', 'list_users',
    '/users/(.*)', 'get_user'
)

app = web.application(urls, globals())

class list_users:        
    def GET(self):
	output = 'users:[';
	for child in root:
                print 'child', child.tag, child.attrib
                output += str(child.attrib) + ','
	output += ']';
        return output

class get_user:
    def GET(self, user):
	for child in root:
		if child.attrib['id'] == user:
		    return str(child.attrib)

if __name__ == "__main__":
    app.run()

4.執行py
./rest.py
5.看結果
http://localhost:8080/users
http://localhost:8080/users/1
http://localhost:8080/users/2
http://localhost:8080/users/3