Create a simple REST web service with Python--转载
2015-09-24 17:23
537 查看
今日尝试用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.htmlCreate 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}[/code]First you will want to install web.py if you don't have it already.sudo easy_install web.pyHere 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.pyThis 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[/code]
相关文章推荐
- python模块imghdr读图片后缀名
- 初学python
- 使用python 的paramiko制作堡垒机
- python matplotlib模块——绘制三维图形、三维数据散点图
- Python 3 抓取网页资源的 N 种方法
- 你可能不知道的python
- Python程序提示SyntaxError: invalid syntax错误
- Python爬取百度贴吧图片
- python:列表推导式,list comprehension
- python处理json
- [LeetCode]题解(python):018-4Sum
- Python 通过print_lol将数据保存到文件中
- python socket编程之select
- Json概述以及python对json的相关操作
- Python快速入门
- head first python读书笔记(十一)
- 猪猪侠那里弄的python递归脚本
- Python 网络爬虫 - 抓取糗事百科的段子(最新版)
- [LeetCode]题解(python):017-Letter Combinations of a Phone Number
- 【Python】BeautifulSoup文档(windows-pyhton2.7.10)