preface

Those of you who have done crawlers are familiar with session and cookie. Simply speaking, cookies are used by clients to identify user information. Session is a kind of session mechanism.

First of all, we need to have a clear understanding of the entire process of cookie: anyone who has done crawler knows that the browser initiates a login request to the server, and the cookie appears in the Response Headers after the login succeeds.

The cookie is then generated from the server and returned to the browser so that the logged in user can access other pages.

For example, after logging in to Taobao, I can access my shopping cart. At this time, the access is successful because the request is accompanied by the cookie after logging in successfully.

If you are not familiar with me, you can take a look at an article I wrote before

Cookie encrypted login to learn about

So the question is how do we set cookies and sessions on the server or in the background?

A, cookie,

Let’s look at how cookies are handled in Flask. In the same way, cookies are obtained from responses, so we set cookies in the response that Flask returns: make_response.

1.1 setting cookies

Flask, by the way, encapsulates the request-related data in the request, and similarly we can set the response-related data using make_response.

from flask import Flask, make_response

app = Flask(__name__)

@app.route('/set_cookie')
def hello_world():
    resp = make_response("success")
    resp.set_cookie("name", "python")
    resp.set_cookie("name2", "go")
    return respCopy the code

The above code sets two cookies. After setting, we start the service and access the address through the browser. Press F12 to see the cookie you set.

You can see the cookies in the response header, and the browser will automatically save them and take them with you the next time you visit.

To verify this, use the following code:

from flask import request

@app.route("/index")
def index():
    cookie = request.cookies
    return f" this is {cookie}"Copy the code

Start, go to http://127.0.0.1:5000/index

There is cookie data in the request header, and the user’s cookie can be obtained in the background.

1.2 Cookie Validity Period

Cookies have an expiration date, careful friends should be able to find that the above cookie does not set an expiration date, close the browser after the cookie will be invalid

In set-cookie, you can use max_age, expires to set the expiration date of a cookie,

Where max_age is in seconds, expires is a timestamp or datetime format for object data

We can add a third cookie data to the hello_world above

@app.route('/set_cookie')
def hello_world():
    resp = make_response("success")
    resp.set_cookie("name", "python")
    resp.set_cookie("name2", "go")
    resp.set_cookie("name3", "jerry", max_age=7200)
    return respCopy the code

After the restart, enter the address in the browser to view cookies

1.3 delete the cookie

The method used to delete the cookie is delete_cookie, we can just pass the key of the cookie that needs to be deleted,

@app.route('/delete')
def delete():
    resp = make_response("delete test")
    resp.delete_cookie("name")
    return respCopy the code

The verification results are as follows:

The creation time and expiration time of name are the same.

Second, the session

The functions of session and cookie are similar in that they both store user-related information. The difference is that session is stored on the server and session_ID is used to identify users. While cookies are stored in the client, the emergence of session is to solve the problem of insecure cookie data storage.

2.1 set up the session

In Flask you can import flask.session to manipulate sessions, much like a dictionary in Python

from flask import session

@app.route("/login")
def login():
    session["name"] = "jerry"
    session["account"] = "python"
    return "success"Copy the code

Note that the SECRET_KEY needs to be set when processing sessions, because Flask uses this value to encrypt and obfuscate sessions.

class Config(object):
    SECRET_KEY = "DJFAJLAJAFKLJQ"

app.config.from_object(Config())Copy the code

2.2 access to the session

Similar to dictionary usage, you can use the get method or the value directly

@app.route("/index")
def index():
    name = session.get("name")
    return f" hello {name}"Copy the code

2.3 delete the session

session.pop("name")
del session["name"]
session.clear()  Copy the code

Clear () clears the session.

That’s all for today. I hope you enjoy it.

To learn more, please pay attention to the public number Python programming and combat