Create a simple REST web service with Python--转载
今日尝试用python建立一个restful服务。
原文地址:http://www.dreamsyssoft.com/python-scripting-tutorial/create-simple-rest-web-service-with-python.php?/archives/6-Create-a-simple-REST-web-service-with-Python.html
Create a simple REST web service with Python
This is a quick tutorial on how to create a simple RESTful web service using python.
The rest service uses web.py to create a server and it will have two URLs, one for accessing all users and one for accessing individual users:
http://localhost:8080/users http://localhost:8080/users/{id}
First you will want to install web.py if you don't have it already.
sudo easy_install web.py
Here is the XML file we will serve up.
<users> <user id="1" name="Rocky" age="38"/> <user id="2" name="Steve" age="50"/> <user id="3" name="Melinda" age="38"/> </users>
The code for the rest server is very simple:
#!/usr/bin/env python 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()
To run your service, simply run:
./rest.py
This creates a web server on port 8080 to serve up the requests. This service returns JSON responses, you can use any of the following URLs to see an example:
http://localhost:8080/users http://localhost:8080/users/1 http://localhost:8080/users/2 http://localhost:8080/users/3