zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    做题遇到的问题集合
    常见算法和数据结构存在的坑(updating)
    Loj#2090. 「ZJOI2016」旅行者(网格图分治)
    洛谷P3332 [ZJOI2013]K大数查询(整体二分板题)
    dij费用流模板
    KM求每个大小的匹配的最优解 模板
    JZOJ 5067. 【GDOI2017第二轮模拟day2】有理有据题 (KD-tree+历史最值问题)
    Codeforces 1186F. Vus the Cossack and a Graph(欧拉回路)
    bzoj#2095. [Poi2010]Bridges(二分+混合图欧拉回路)
    二维最小乘积生成树模板
  • 原文地址:https://www.cnblogs.com/ak918xp/p/13766809.html
Copyright © 2011-2022 走看看