zoukankan      html  css  js  c++  java
  • flask 第六篇 flask内置的session

    Flask中的Session非常的奇怪,他会将你的SessionID存放在客户端的Cookie中,使用起来也非常的奇怪

    1. Flask 中 session 是需要 secret_key 的

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

    secret_key 实际上是用来加密字符串的,如果在实例化的app中没有 secret_key 那么开启session一定会抛异常的

    2. session 要这样用

     
    @app.route("/login", methods=["GET", "POST"])
    def login():
        if request.method == "POST":
            if request.form["username"] == USER["username"] and request.form["password"] == USER["password"]:
                session["user"] = USER["username"]
                return redirect("/student_list")
            return render_template("login.html", msg="用户名密码错误")
    
        return render_template("login.html", msg=None)  # 如果前端Jinja2模板中使用了msg,这里就算是传递None也要出现msg
     

    session["user"] = USER["username"] 这样用就代表这个请求带上来的session中保存了一个user=name
    如果想要验证session的话,就用这种方法吧

    3. cookies 中的 session 是什么

    cookies 中 session 存储的是通过 secret_key 加密后的 key , 通过这个 key 从flask程序的内存中找到用户对应的session信息

    4. 怎么用 session 进行验证呢?

     
    @app.route("/student_list")
    def student():
        if session.get("user"):
            return render_template("student_list.html", student=STUDENT_DICT)
    
        return redirect("/login")
     

    第六篇,完结

  • 相关阅读:
    poj 2312 Battle City
    poj 2002 Squares
    poj 3641 Pseudoprime numbers
    poj 3580 SuperMemo
    poj 3281 Dining
    poj 3259 Wormholes
    poj 3080 Blue Jeans
    poj 3070 Fibonacci
    poj 2887 Big String
    poj 2631 Roads in the North
  • 原文地址:https://www.cnblogs.com/lingcai/p/10434136.html
Copyright © 2011-2022 走看看