zoukankan      html  css  js  c++  java
  • Flask_cookie和session

    1.cookie的设置和获取

      设置:response.set_cookie(key, value, max_age)

         max_age:表示在浏览器的存储时间,单位是秒。

      获取:request.cookies.get("key")

    from flask import Flask, make_response, request
    
    app = Flask(__name__)
    
    
    @app.route('/set')
    def set_cookie():
        # 调用make_response方法获取相应体对象
        response = make_response('cookie设置完毕!')
        # 设置cookie
        response.set_cookie("key1", "wdc")
        return response
    
    @app.route('/get')
    def get_cookie():
        # 获取cookie
        value = request.cookies.get('key1')
    
        return f"cookie的值为{value}"
    
    if __name__ == '__main__':
    
        app.run()

     2.session的设置和获取

      设置:session[key] = value

      获取:value = session.get(key)

      注意:session的存储依赖于cookie,存储在cookie中的sessionID需要加密,需要密钥(SECRET_KEY)。

    from flask import Flask, session
    
    app = Flask(__name__)
    # 设置密钥
    app.config["SECRET_KEY"] = "wdc"
    
    # 设置session
    @app.route('/set/<name>')
    def set_session(name):
        session["name"] = name
    
        return "set session!"
    
    # 获取session
    @app.route('/get')
    def get_session():
    
        value = session.get("name")
    
        return f"session的值为{value}"
    
    if __name__ == '__main__':
    
        app.run()
  • 相关阅读:
    poj3608Bridge Across Islands(旋转卡壳)
    旋转卡壳(rotate吧)
    旋转卡壳(rotate吧)
    poj2187 Beauty Contest
    poj2187 Beauty Contest
    poj1637 Sightseeing tour
    poj1637 Sightseeing tour
    bzoj2756 [SCOI2012]奇怪的游戏
    bzoj2756 [SCOI2012]奇怪的游戏
    noip胡测之8.15(没有正解)
  • 原文地址:https://www.cnblogs.com/wangdianchao/p/13693603.html
Copyright © 2011-2022 走看看