我需要创建以下...使用RESTful设计模式来实现以下URI的基本Web服务:
http://localhost/hello?name=”world”
上述URI应该返回以下JSON格式的文本:
{ hello: “world” }
但是我很难弄清楚这一点以及将其放置在已经创建的代码中的位置。
#!/usr/bin/python
import json
from bson import json_util
import bottle
from bottle import route, run, request, abort
# set up URI paths for REST service
@route('/currentTime', method='GET')
def get_currentTime():
dateString=datetime.datetime.now().strftime("%Y-%m-%d")
timeString=datetime.datetime.now().strftime("%H:%M:%S")
string="{\"date\":"+dateString+",\"time\":"+timeString+"}"
return json.loads(json.dumps(string, indent=4,default=json_util.default))
if __name__ == '__main__':
#app.run(debug=True)
run(host='localhost', port=8080)
答案 0 :(得分:0)
动态编程是您使用API的最佳选择。
from bottle import Bottle, get, post, request, response, route, abort, template, redirect, run
import ujson as json
import datetime
from bson import json_util
class Api(object):
def __init__(self, request, option):
self.option = option
self.payload = merge_dicts(dict(request.forms), dict(request.query.decode()))
def currentTime(self):
dateString=datetime.datetime.now().strftime("%Y-%m-%d")
timeString=datetime.datetime.now().strftime("%H:%M:%S")
string="{\"date\":"+dateString+",\"time\":"+timeString+"}"
return string
def hello(self):
return {'hello' : self.payload['name']}
@get('/api/<command>')
@post('/api/<command>')
@get('/api/<command>/<option>')
@post('/api/<command>/<option>')
def callapi(command = None, option = None):
A = Api(request, option)
func = getattr(A, "{}" .format(command), None)
if callable(func):
result = func()
if result:
if request.method == 'GET':
response.headers['Content-Type'] = 'application/json'
response.headers['Cache-Control'] = 'no-cache'
return json.dumps(result, indent=4,default=json_util.default)
else:
return json.dumps({})
def merge_dicts(*args):
result = {}
for dictionary in args:
result.update(dictionary)
return result
if __name__ == '__main__':
#app.run(debug=True)
run(host='localhost', port=8080)
它的作用是让您现在可以简单地在Api类下创建新函数,它们动态地成为URL路由。如果需要,您可以通过请求在API方法中检查发布或获取信息。我合并了来自表单或查询字符串的有效负载,以便您可以接受其中任何一个,并且将其视为单个有效负载。
该选项只是在您希望为路由提供更多功能的情况下。