python构建restful服务

来源:互联网 发布:navicat linux 注册码 编辑:程序博客网 时间:2024/06/07 15:47

python构建restful服务

一、目的:

    创建简单的restful服务,实现userid和port的映射。

二、使用组件:

1.restful web框架:

web.py(http://webpy.org/install.zh-cn)

    安装web.py:

 sudo pip install web.py

2.xml解析框架:

ElementTree

三、代码如下:

#!/usr/bin/python

import web

from xml.etree import ElementTree as ET

urls=(

'/users/(.*)','handler'

)

app = web.application(urls,globals())

 

allusers=ET.parse('user.xml')

user=allusers.findall('./user')

 

class handler:

    def GET(self,userid):

        for x in user:

            if x.attrib['id'] == userid:

                    return x.text

 

if __name__ == "__main__":

    app.run()

配置文件:

<?xml version="1.0" encoding="utf-8"?>

<users>

    <user id="xxxxxxxx">29264</user>

    <user id="yyyyyyyy">10000</user>

</users>

 四、使用:

启动: python user_port.py

调用:

curl http://localhost:8080/users/xxxxxxxx
29264

 

 

 

原创粉丝点击