Redirect Flask framework, cookie and session

A, URL redirection (redirect)

app.route @ ( " / the Login " )
 DEF the Login ():
     # Use url_for function to find the url path through the name of the view function 
    url = url_for ( " index " )
     return redirect (url)

Two, cookie operations

@app.route("/")
def index():
    RESP = make_response ( " SET Cookie IS OK " )
     # Set Cookie 
    resp.set_cookie ( " name " , " YY " )
     # by max_age set the expiration time in seconds 
    resp.set_cookie ( " Age " , " 18 is " , max_age = 3600 )
     return RESP


@app.route("/cookie")
def cookie():
    # 获取cookie
    name = request.cookies.get("name")
    return name

@app.route("/delete")
def delete_cookie():
    resp = make_response("delete ok")
    # 删除cookie
    resp.delete_cookie("name")
    return resp

Three, session operation

# Flask session will be used in the key string of 
the app.config [ ' of SECRET_KEY ' ] = os.urandom (24 )
 # default session expiration of 30 days, the following code is set to expire five hours 
the app.config [ ' PERMANENT_SESSION_LIFETIME ' ] = timedelta (=. 5 hours )


@app.route("/login")
def login():
    # 设置session
    session["username"] = "yy"
    session["password"] = "admin"
    session["data"] = {"a": 1, "b": 2}
    return redirect(url_for("index"))


@app.route("/index")
def index():
    data = session.get("data")
    if data is None:
        return "None"
    return str(data)


@app.route("/delete")
def delete():
    # 删除session
    # del session['username']
    session.clear()
    return "ok"

 

Guess you like

Origin www.cnblogs.com/yang-2018/p/11013353.html