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

  • 相关阅读:
    Go语言的性能测试对比
    学习笔记
    使用TCPDump分析Redis的Pipeline比Multi更快的原因
    基于Redis/Memcached的高并发秒杀设计
    这些 .Net and Core 相关的开源项目,你都知道吗?(持续更新中...)
    《.Net 的冰与火之歌》寄雁传书,你必须知道的C#参数知识大盘点
    分享自己的超轻量级高性能ORM数据访问框架Deft
    Expression2Sql的一些语法更新
    介绍一个可以将Expression表达式树解析成Transact-SQL的项目Expression2Sql
    记一次随机字符串生成算法的随机概率与性能的提升
  • 原文地址:https://www.cnblogs.com/ak918xp/p/13766809.html
Copyright © 2011-2022 走看看