python flask restful api 统计分析_python之restful api(flask)获取数据

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

1.直接上代码

1 from flask import Flask

2 from flask import request

3 from flask import abort

4 from flask import jsonify

5 import re

6

7 app = Flask(__name__)

8

9 @app.route('/')

10 def index():

11 return 'hello world'

12

13

14 @app.route('/message/',methods=['GET'])

15 def get_message(message_id):

16 if message_id == 'all':

17 search = 'all'

18 else:

19 if re.match(r'^\d+$',message_id):

20 search = int(message_id)

21 else:

22 abort(400)

23

24 messages = [{'id':1,'site':'baidu'},{'id':2,'site':'taobao'}]

25 res = {}

26

27 if search == 'all':

28 res['result'] = messages

29 res['status'] = 'success'

30 else:

31 for item in messages:

32 if item['id'] == search:

33 res['result'] = [item]

34 res['status'] = 'success'

35 break

36 if 'result' not in res:

37 res['status'] = 'error'

38 res['content'] = 'id is not in range'

39 if request.headers['Content-Type'] == 'application/json':

40 return jsonify(res),{'Content-Type':'application/json'}

41 elif request.headers['Content-Type'] == 'text/xml':

42 return '',{'Content-Type':'text/xml'}

43 else:

44 return str(res)

45

46

47 if __name__ == '__main__':

48 app.run(port=5100)

代码解释:

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

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

代码中的abort:触发400错误即报Bad RequestThe 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,flask,restful,api,统计分析)