The Advanced Rest Client, an extension program of Google browser, is required for simulation request
1. Code directly
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/<message_id>',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 40 if request.headers['Content-Type'] == 'application/json': 41 return jsonify(res),{'Content-Type':'application/json'} 42 elif request.headers['Content-Type'] == 'text/xml': 43 if 'result' not in res: 44 return '''<?xml version="1.0"?> 45 <objects> 46 <status>%s</status> 47 <content>%s</content> 48 </objects> 49 '''%(res['status'],res['content']),{'Content-Type':'text/xml'} 50 else: 51 res_head = '<?xml version="1.0"?><objects><result>' 52 res_foot = '</result><status>success</status></objects>' 53 res_body = '' 54 for item in res['result']: 55 res_body += '<item id=""><id></id><site></site></item>'.format(id=item['id'],site=item['site']) 56 res_whole = res_head + res_body + res_foot 57 return res_whole,{'Content-Type':'text/xml'} 58 else: 59 return str(res) 60 61 62 63 if __name__ == '__main__': 64 app.run(port=5100)
Code interpretation
restful api Request Routing: / message / < message_id >, message_id is all or integer
Data source: messages = [{'id':1,'site':'baidu'},{'id':2,'site':'taobao'}]
abort in the code: if the 400 error is triggered, the message Bad Request the browser (or proxy) send a request that this server could not understand. When the message "Ou ID" is not all or an integer number
Note: when testing the request, the Advanced Rest Client should not specify Accept in the Headers (because it can Accept multiple types), but the content type
The return value does not use the status code, but determines whether the status in the return value is success or error
2. Test result chart directly
Note: if you don't understand it, you can send it to the blogger