您可以捐助,支持我们的公益事业。

1元 10元 50元





认证码:  验证码,看不清楚?请点击刷新验证码 必填



  求知 文章 文库 Lib 视频 iPerson 课程 认证 咨询 工具 讲座 Model Center   Code  
会员   
   
 
     
   
 订阅
  捐助
使用python创建一个简单的restful风格的webservice应用
 
  8913  次浏览      15
 2017-12-29  
 
编辑推荐:
本文来自于dreamsyssoft.com ,这是一个如何使用python快速构建简单restful风格webservice的应用教程,整个流程介绍较为详细可供大家参考。

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

1.分析rest路由规则

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

一个是为了查询所有用户,一个是为了查询单个用户。

例如下面的url:

http://localhost:8080/users

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

2.搭建web.py环境

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

sudo easy_install web.py

3.提供数据源

下面是一个提供数据的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>

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应用建立完毕。

   
8913 次浏览       15
相关文章

企业架构、TOGAF与ArchiMate概览
架构师之路-如何做好业务建模?
大型网站电商网站架构案例和技术架构的示例
完整的Archimate视点指南(包括示例)
相关文档

数据中台技术架构方法论与实践
适用ArchiMate、EA 和 iSpace进行企业架构建模
Zachman企业架构框架简介
企业架构让SOA落地
相关课程

云平台与微服务架构设计
中台战略、中台建设与数字商业
亿级用户高并发、高可用系统架构
高可用分布式架构设计与实践