zoukankan      html  css  js  c++  java
  • Create a simple REST web service with Python--转载

    今日尝试用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.html

    Create 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}

    First you will want to install web.py if you don't have it already.

    sudo easy_install web.py

    Here 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.py

    This 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
  • 相关阅读:
    C# 解析JSON字符串
    C# 调用SAP RFC
    【Vue】vue动态添加表单项
    2020年余额不足,送你3本Python好书充值
    中国编程第一人,一人抵一城!
    2020年测试工作总结!
    这段代码,我在本地运行没问题啊
    我28岁,财务自由168天,却写下一封遗书...
    困惑大家这么多年的区块链技术,终于被沈阳一小区大门给讲明白了
    年轻人越来越有出息的迹象
  • 原文地址:https://www.cnblogs.com/javajava/p/4835926.html
Copyright © 2011-2022 走看看