【译】使用python建立一个简单的restful风格的webservice应用

这是一个如何使用python快速构建简单restful风格webservice的应用教程。  python

1.分析rest路由规则

 rest风格的服务一般使用web.py来建立服务器端脚本,通常状况下包含两个url路径: web

 一个是为了查询全部用户,一个是为了查询单个用户。 json

例以下面的url: 服务器

http://localhost:8080/usersrestful

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

2.搭建web.py环境

首先你应该安装web.py模块到你的python环境下。若是你以前没有的话请执行下面的脚本。url

sudo easy_install web.pyspa

3.提供数据源 

下面是一个提供数据的XML文件 .net

user_data.xml rest


?

1
2
3
4
5
6
7
8
9
< users >
 
     < user id = "1" name = "Rocky" age = "38" />
 
     < user id = "2" name = "Steve" age = "50" />
 
     < user id = "3" name = "Melinda" age = "38" />
 
</ users >


4.提供服务器端程序

代码清单一:提供一个简单rest服务的python代码

rest.py

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2014-08-04 14:03:19
# @Author  : pinghailinfeng (pinghailinfeng79@gmail.com)
# @Link    : http://my.oschina.net/dlpinghailinfeng
# @Version : $Id$
 
import web
import xml.etree.ElementTree as ET
 
tree = ET.parse( 'users.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()

5.运行脚本

接下来运行这个脚本

./rest.py

6.访问url

默认是在8080端口提供能够访问的service服务。这个API服务返回的是json数据,你能够使用下面任意一个URL路径访问,例如:

http://localhost:8080/users

http://localhost:8080/users/1

http://localhost:8080/users/2

http://localhost:8080/users/3

7.结果


 


 

至此,一个简单的restful风格的webservice应用创建完毕。

下面继续研究web.py的其余内容

相关文章
相关标签/搜索