【Flask】Flask Cookies

Flask Cookies

Cookies are stored in the form of text files on the client's computer. Its purpose is to remember and track data related to customer usage in order to obtain a better visitor experience and website statistics.

The Request object contains the attributes of Cookie. It is a dictionary object of all cookie variables and their corresponding values, which the client has transmitted. In addition, the cookie also stores the expiration time, path and domain name of its website.

In Flask, the processing steps for cookies are:

1. Set cookie:

    Set a cookie, the default validity period is a temporary cookie, and it will become invalid when the browser is closed

    The validity period can be set by max_age, the unit is second

 resp = make_response("success")   # 设置响应体
 resp.set_cookie("w3cshool", "w3cshool", max_age=3600)

  2. Get cookies

    Get the cookie, through reques.cookies, the return is a dictionary, you can get the corresponding value in the dictionary

cookie_1 = request.cookies.get("w3cshool")

3. Delete cookies

    The deletion here just expires the cookie, not directly deletes the cookie

    Delete the cookie by way of delete_cookie(), which contains the name of the cookie

resp = make_response("del success")  # 设置响应体
resp.delete_cookie("w3cshool")

The following is a simple example of Flask Cookies:

from flask import Flask, make_response, request

app = Flask(__name__)

@app.route("/set_cookies")
def set_cookie():
    resp = make_response("success")
    resp.set_cookie("w3cshool", "w3cshool",max_age=3600)
    return resp

@app.route("/get_cookies")
def get_cookie():
    cookie_1 = request.cookies.get("w3cshool")  # 获取名字为Itcast_1对应cookie的值
    return cookie_1

@app.route("/delete_cookies")
def delete_cookie():
    resp = make_response("del success")
    resp.delete_cookie("w3cshool")

    return resp

if __name__ == '__main__':
    app.run(debug=True)

 

Set cookies

Run the application, enter 127.0.0.1:5000/set_cookies in the browser to set cookies, the output of setting cookies is as follows:

 

Get cookie

According to the corresponding path in the view function, enter http://127.0.0.1:5000/get_cookies and the output of reading back cookies is as follows:

 

Delete cookie

According to the corresponding path in the view function, enter http://127.0.0.1:5000/delete_cookies and the output of deleting cookies is as follows:

 

Be careful to delete, just let the cookie expire.

Guess you like

Origin blog.csdn.net/u013066730/article/details/108360906