Specific use of flash response response

Time:2021-11-28
catalogue
  • introduction
  • Response response
    • Tuple form response
    • make_ Response function
    • Return JSON format data
  • Other special responses
    • Redirect
    • Abort() interrupt
  • source code

    introduction

    The client sends an HTTP request to the flash program. After flash calls the view function, it will take its return value as the content of the response. In most cases, the response is a simple string, which is sent back to the client as an HTML page.
    But the HTTP protocol needs more than just a string in response to a request. A very important part of the HTTP response is the status code. If flag is set to 200, it means that the request has been successfully processed.

    Response response

    Tuple form response

    If the response returned by the view function needs to use different status codes, you can add the numeric code as the second return value after the response text

    from flask import Flask
    
    app = Flask(__name__)
    
    
    #Returns the response information in tuple form
    @app.route("/index")
    def index():
        #Responder status code
        return "index page", 400

    The response returned by the view function can also accept the third parameter, and the response header can be returned later, for example:

    from flask import Flask
    
    app = Flask(__name__)
    
    
    #Returns the response information in tuple form
    @app.route("/index")
    def index():
        header_dict = {
            "name": "jack",
            "age": 22
        }
    
        header_list = [("name", "hui"), ("age", 21)]
    
        #Response body status code response header
        return "index page", 400, header_dict
        # return "index page", 400, header_list

    However, the response header information should be wrapped in a dictionary or list. The dictionary is easy to understand, and the list stores the response header information in the form of tuples. What is returned here is just an example. When returning, you should reasonably set the response header information, such as

    header_dict = {
        "Content type": "text / HTML; charset = UTF-8"
        "Set cookie": "name = Hui; path = /" # response setting cookie "
    }
    return "index page", 200, header_dict

    Browser developer tool to view response information

    Remember: it is returned in tuple form, and the position of the return value cannot be disordered

    First corresponding responder
    The second corresponding status code
    Third corresponding response header

    make_ Response function

    If you do not want to return a tuple of 1, 2, or 3 values, the flame view function can also return a response object. make_ The response function can accept 1, 2 or 3 parameters (the same as the return value of the view function) and return a response object. See how to use it

    from flask import Flask, make_response
    
    app = Flask(__name__)
    
    # mk_ Response sets the response information
    @app.route("/info")
    def info():
        resp = make_response("info page")
        resp.status = "666 ithui"
        resp.headers["name"] = "hui"
        resp.headers["age"] = 21
        return resp

    Note: make_ The response () object must be a string when setting the status code, not a number

    Return JSON format data

    
    import json
    from flask import Flask, make_response
    
    app = Flask(__name__)
    
    
    @app.route("/json")
    def resp_json():
        data = {
            "name": "hui",
            "age": 21
        }
    
        json_str = json.dumps(data)
        headers = {"Content-Type": "application/json"}
        return json_str, 200, headers
    
    

    You can use the JSON module to JSON data, but generally, the data type returned by the front end should be set when returning JSON data. The default of flash is text / HTML, so we need to set the content type of the response body separately.

    Because JSON format data is frequently used in web development, the jsonify () function is specially provided in flash to respond to JSON data

    The specific use is as follows

    
    from flask import Flask, jsonify
    
    app = Flask(__name__)
    
    
    @app.route("/json")
    def resp_json():
        data = {
            "name": "hui",
            "age": 21
        }
        return jsonify(data)
        # return jsonify(name="jack", age=20)
    
    

    Jsonify () can receive a dictionary or construct JSON data in the form of key value. This is much more convenient

    Other special responses

    Redirect

    There is a special response type called redirection. This response type has no page document and only tells the browser a new address to load the new page

    from flask import Flask, redirect
    
    app = Flask(__name__)
    
    #Set the redirection information yourself
    @app.route('/baidu')
    def red_baidu():
        resp = make_response()
        resp.status = "302"
        resp.headers['Location'] = "http://www.baidu.com"
        return resp
    
    
    #Redirect response redirection
    @app.route("/csdn")
    def red_csdn():
        csdn_url = "https://blog.csdn.net/qq_43629857"
        return redirect(csdn_url)

    Redirection is often represented by 302 status code, and the address pointed to is provided by the location header. Because of its frequent use, flask provides the auxiliary function redirect (), which is used to generate this response.

    Abort() interrupt

    Abort() receives a status code parameter

    from flask import Flask, request, abort
    
    app = Flask(__name__)
    
    #Abort interrupt
    # http://127.0.0.1:5000/login?name=hui&pwd=123
    @app.route("/login", methods=['GET'])
    def login():
        name = request.args.get("name")
        pwd = request.args.get("pwd")
        if name != "hui" or pwd != "123":
            abort(404)
    
        Return "login succeeded."

    Generally, this abort() function will be used together with the error information processing decorator app. Errorhandler(), as follows:

    #Processing 404 status error
    @app.errorhandler(404)
    def handle_404_err(err):
        Return F "404 error message {err}"
    
    
    #Processing 500 status errors
    @app.errorhandler(500)
    def handle_500_err(err):
        Return F "500 server error {err}"
    
    
    #Abort interrupt
    # http://127.0.0.1:5000/login?name=hui&pwd=123
    @app.route("/login", methods=['GET'])
    def login():
        name = request.args.get("name")
        pwd = request.args.get("pwd")
        if name != "hui" or pwd != "123":
            abort(404)
    
        Return "login succeeded."

    source code

    The source code has been uploaded to gitee huidbk / flashbasic – Code cloud – Open Source China (gitee. Com). Welcome to visit.

    This is the end of this article on the specific use of flash response. For more information about flash response, please search for previous articles of developeppaer or continue to browse the following articles. I hope you will support developeppaer in the future!