exercise 3:Python Flask
1. Preparation
1.1. Flask Flask is a web framework for Python, meaning that it provides functionality for building web applications, including managing HTTP requests and rendering templates.
Open a command prompt.
#Install Flask using the pip package manager for Python: pip install flask #Install requests library (if you have not done so) pip install requests
1.2. JSON Formatter To view JSON in chrome browser, install the plugin JSON Formatter.
https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa
1.3. Postman and curl Download postman and curl for sending and viewing HTTP request and responses
https://www.postman.com/downloads/
https://curl.haxx.se/download.html
2. Python Flask
2.1. Basics Create a python script application.py.
from flask import Flask, request, jsonify import json app = Flask(__name__) @app.route('/', methods=['GET']) def hello(): return 'Hello!!!', 200 if __name__ == '__main__': app.run(host='127.0.0.1', port=5000, debug=True)
The process of mapping URLs to functions is called routing. The @app.route('/', methods=['GET'])
syntax is the part of the program that lets Flask know that this function, hello, should be mapped to the path /. The methods list (methods=['GET']) is a keyword. The return value 200 is HTTP the response code to be returned to client.
from datetime import datetime @app.route('/datetime', methods=['GET']) def print_today(): return str(datetime.now()), 200
You can add variable sections to a URL by marking sections with <variable_name>. Your function then receives the <variable_name> as a keyword argument. Optionally, you can use a converter to specify the type of the argument like <converter:variable_name>.
Add the following route to the flask server script.
@app.route('/users/<username>') def get_user(username): return "user: "+str(username),200
You may access the location http://localhost/users/alice to check if the name parameter is printed.
2.2. Query strings
Suppose that we want to implement an add function with two operands passed as query string parameters. The operands and the sum will be returned to the client as a JSON object.
@app.route('/add', methods=['GET']) def add(): a = int(request.args['op1']) b = int(request.args['op2']) return jsonify({"operand 1": a, "operand 2": b, "sum":a+b}) #return JSON object
Sample output: http://localhost:5000/add?op1=3&op2=4
Modify the add() function as follows.
@app.route('/add', methods=['GET']) def add(): if 'op1' in request.args.keys() and 'op2' in request.args.keys(): a = int(request.args['op1']) b = int(request.args['op2']) return jsonify({"operand 1": a, "operand 2": b, "sum":a+b}) #return JSON object else: return jsonify({'error':'missing parameter(s)'})
Sample output: http://localhost:5000/add?op1=3
2.3. Viewing the HTTP messages in Postman
You may use Postman to view the detailed HTTP request and response (including the response code).
Example: HTTP response code 200 OK is returned.
使用postman工具
显示原始日志
2.4. HTTP POST
Data can be sent in the HTTP message body from the client to the HTTP server using HTTP POST method. Add the following function to the python script.
@app.route('/mul', methods=['POST']) def mul(): print("multiply") data = request.json # get json data from request body a = data["op1"] b = data["op2"] return jsonify({'mul': a * b}), 200