【譯】使用python建立一個簡單的restful風格的webservice應用


這是一個如何使用python快速構建簡單restful風格webservice的應用教程。 python

1.分析rest路由規則

 rest風格的服務一般使用web.py來建立服務器端腳本,通常狀況下包含兩個url路徑: web

 一個是爲了查詢全部用戶,一個是爲了查詢單個用戶。 json

例以下面的url: 服務器

http://localhost:8080/users restful

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

2.搭建web.py環境

首先你應該安裝web.py模塊到你的python環境下。若是你以前沒有的話請執行下面的腳本。 url

sudo easy_install web.py spa

3.提供數據源 

下面是一個提供數據的XML文件 .net

user_data.xml rest


<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

#!/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的其餘內容

相關文章
相關標籤/搜索