python之restful api(flask)获取数据

需要用到谷歌浏览器的扩展程序 Advanced Rest Client进行模拟请求

1.直接上代码

 from flask import Flask
from flask import request
from flask import abort
from flask import jsonify
import re app = Flask(__name__) @app.route('/')
def index():
return 'hello world' @app.route('/message/<message_id>',methods=['GET'])
def get_message(message_id):
if message_id == 'all':
search = 'all'
else:
if re.match(r'^\d+$',message_id):
search = int(message_id)
else:
abort(400) messages = [{'id':1,'site':'baidu'},{'id':2,'site':'taobao'}]
res = {} if search == 'all':
res['result'] = messages
res['status'] = 'success'
else:
for item in messages:
if item['id'] == search:
res['result'] = [item]
res['status'] = 'success'
break
if 'result' not in res:
res['status'] = 'error'
res['content'] = 'id is not in range' if request.headers['Content-Type'] == 'application/json':
return jsonify(res),{'Content-Type':'application/json'}
elif request.headers['Content-Type'] == 'text/xml':
if 'result' not in res:
return '''<?xml version="1.0"?>
<objects>
<status>%s</status>
<content>%s</content>
</objects>
'''%(res['status'],res['content']),{'Content-Type':'text/xml'}
else:
res_head = '<?xml version="1.0"?><objects><result>'
res_foot = '</result><status>success</status></objects>'
res_body = ''
for item in res['result']:
res_body += '<item id="{id}"><id>{id}</id><site>{site}</site></item>'.format(id=item['id'],site=item['site'])
res_whole = res_head + res_body + res_foot
return res_whole,{'Content-Type':'text/xml'}
else:
return str(res) if __name__ == '__main__':
app.run(port=5100)

代码解释

  restful api请求路由:/message/<message_id>,message_id为 all 或者 整型数字  

  数据源:messages = [{'id':1,'site':'baidu'},{'id':2,'site':'taobao'}]

  代码中的abort:触发400错误即报Bad Request  The browser (or proxy) sent a request that this server could not understand. ,当message_id不是all 也不是整型数字时

  注意一点:Advanced Rest Client 测试请求时不要在Headers指定Accept(因为它可以接受多种类型),而应该指定Content-Type

  返回值没有用到状态码,而是通过判断返回值中的status是success还是error

2.直接上测试结果图

python之restful api(flask)获取数据

python之restful api(flask)获取数据

python之restful api(flask)获取数据

python之restful api(flask)获取数据

python之restful api(flask)获取数据

python之restful api(flask)获取数据

python之restful api(flask)获取数据

python之restful api(flask)获取数据

注:有不懂的可以私信博主本人

上一篇:正则表达式——POSIX字符组


下一篇:php微信支付测试开发(流程已通)