This article is participating in Python Theme Month. See the link to the event for more details


The introduction

The client sends an HTTP request to Flask. Flask calls the view function and returns the value as the content of the response. In most cases, the response is a simple string that is sent back to the client as an Html page.

But the HTTP protocol requires more than strings that respond to requests. An important part of the HTTP response is the status code. Flask is set to 200 to indicate that the request was processed successfully.


The response response

Tuple response

If the response returned by the view function also requires a different status code, you can add the numeric code as the second return value after the response text

from flask import Flask

app = Flask(__name__)


Return the response information as a tuple
@app.route("/index")
def index() :
    # Response body status code
    return "index page".400
Copy the code


The response returned by the view function can also take a third argument, and the response header can be returned after it. For example:

from flask import Flask


app = Flask(__name__)


Return the response information as a tuple
@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
    
Copy the code


But the response header should be wrapped in a dictionary or list. The dictionary is easy to understand, and the list stores the response header as a tuple. This is just an example. When you do return, you should set the response header appropriately, for example

header_dict = {
    "Content-Type": " text/html; charset=utf-8".# The data type returned by the response
    "Set-Cookie": "name=hui; Path=/"    	   # Response set cookie
}
return "index page".200, header_dict   
Copy the code


Browser developer tools view response information


Remember: return as a tuple, return value position can not be messed up

  • The first one corresponds to the response body
  • The second corresponds to the status code
  • The third corresponds to the response header


Make_response function

The Flask view function can also return a Response object if you don’t want to return a tuple of 1, 2, or 3 values. The make_response function can take one, two, or three arguments (the same as the return value of the view function) and return a Response object. 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
Copy the code


Note:make_response()Object setting status code must be a string, not a number


Returns data in JSON format

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
Copy the code

You can json your data with the JSON module, but usually you need to set the type of data that the front end returns. Flask defaults to TEXT/HTML, so you need to set the content type of the response body separately.

Since JSON format data is used frequently in Web development, a jsonify() function is provided in Flask 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)
Copy the code

Jsonify () can receive a dictionary or construct JSON data in key-value form. It’s much more convenient


Other special responses

Redirect redirect ()

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

from flask import Flask, redirect

app = Flask(__name__)

Set your own redirection information
@app.route('/baidu')
def red_baidu() :
    resp = make_response()
    resp.status = "302"
    resp.headers['Location'] = "http://www.baidu.com"
    return resp


# redirect Redirect responses
@app.route("/csdn")
def red_csdn() :
    csdn_url = "https://blog.csdn.net/qq_43629857"
    return redirect(csdn_url)
Copy the code

Redirects are often denoted with a 302 status code and point to an address provided by the Location header. Because of the frequent use, Flask provides the helper function redirect() to generate this response.


Abort ()

Abort () receives a status code argument

from flask import Flask, request, abort

app = Flask(__name__)

# abort the 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")
    ifname ! ="hui" orpwd ! ="123":
        abort(404)

    return "Login successful"
Copy the code


The abort() function is used with the errorhandler decorator app.errorhandler(), which looks like this:

# Handle 404 status error
@app.errorhandler(404)
def handle_404_err(err) :
    return F "404 Error message{err}"


# Handle 500 status error
@app.errorhandler(500)
def handle_500_err(err) :
    return F "500 Server error{err}"


# abort the 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")
    ifname ! ="hui" orpwd ! ="123":
        abort(404)

    return "Login successful"
Copy the code


The source code

The source code has been uploaded to Gitee HuiDBK/FlaskBasic – Code Cloud – Open Source China (gitee.com), welcome to visit.

✍ code word is not easy, still hope you heroes support ❤️.


The public,

Create folder X

It took nature tens of billions of years to create our real world, and programmers hundreds of years to create a completely different virtual world. We hammer out bricks with keyboards and build everything with brains. People see 1000 as the authority, we do the opposite and defend 1024. We are not keyboard heroes, we are just extraordinary builders of the ordinary world.