【Flask】Session

usage

Flask of Session is very strange that he will put your SessionID is stored in the client's Cookie, the use is also very strange

Flask of the session is required secret_key

from flask import session
app = Flask(__name__)
app.secret_key = "henry"

secret_key actually used to encrypt the string, if not secret_key then open session in the instance of the app will throw an exception in the

Copy the code
from flask import Flask,render_template,request,session,redirect

app = Flask(__name__)
# 设置secret_key
app.secret_key = "123456"
app.debug = True
# app.config["DEBUG"] = True

@app.route('/login',methods=["POST","GET"])
def login():
    if request.method == "GET":
        return render_template("login.html")

    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        if username == "henry" and password == "123456":
            # 登录成功设置session
            session["username"] = username
            return redirect('index')
        else:
            return "404"

app.route @ ( '/ index') 
DEF index (): 
    # check whether the logged-on user 
    IF Session.get ( "username"): 
        return "This is the index page" 
    the else: 
        return redirect ( 'the Login') 
IF __name__ = = '__main__': 
    app.run ( "0.0.0.0", 9876)
Copy the code

What are cookies of session

cookies are stored in the session key by the encryption secret_key find session information corresponding to the user from the program memory by this flask key

 

 

Guess you like

Origin www.cnblogs.com/youxiu123/p/11605776.html