zoukankan      html  css  js  c++  java
  • flasksession

    flask-session

    一、flask-session使用

    作用:将默认保存的签名cookie中的值 保存到 redis/memcached/file/Mongodb/SQLAlchemy

    安装:pip3 install flask-session

    from flask import Flask, session
    from flask_session import RedisSessionInterface
    import redis
    
    app = Flask(__name__)
    
    conn = redis.Redis(host='127.0.0.1', port=6379)
    
    # app.session_interface
    app.secret_key = 'sdfdsfds' 
    app.session_interface = RedisSessionInterface(conn, key_prefix='randy', use_signer=True, permanent=False)
    
    
    @app.route('/')
    def hello_world():
        session['name'] = 'randy'
        return 'Hello World!'
    
    
    @app.route("/index")
    def index():
        print(session['name'])
        return "ok"
    
    
    if __name__ == '__main__':
        app.run()
    
    

    参数

    • conn:连接数据库
    • key_prefix='randy:前缀
    • 'use_signer=True:默认为Flase, 则不需设置secret_key
    • permanent=False: 关闭浏览器删除cookies,默认为true,不删除

    二、flask-session封装

    # 封装配置 
    app.config['SESSION_TYPE'] = 'redis'
    app.config['SESSION_REDIS'] = Redis(host='127.0.0.1', port='6379')
    Session(app)
    
    from flask import Flask, session
    from redis import Redis
    from flask_session import Session
    
    app = Flask(__name__)
    app.config['SESSION_TYPE'] = 'redis'
    app.config['SESSION_REDIS'] = Redis(host='127.0.0.1', port='6379')
    Session(app)
    
    
    @app.route('/')
    def hello_world():
        session['name'] = 'randy'
        return 'Hello World!'
    
    
    @app.route("/index")
    def index():
        print(session['name'])
        return "ok"
    
    
    if __name__ == '__main__':
        app.run()
    
    

    三、总结

    • 本身都是修改了app.session_interface的类

    • 问题:设置cookie时,如何设定关闭浏览器则cookie失效。

      from flask import Response
      Response.set_cookie('k','v',exipre=None)#这样设置即可
      #在session中设置
      app.session_interface=RedisSessionInterface(conn,key_prefix='randy',permanent=False)
      #一般不用,我们一般都设置超时时间,多长时间后失效
      

      问题:cookie默认超时时间是多少?如何设置超时时间

      #源码expires = self.get_expiration_time(app, session)
      'PERMANENT_SESSION_LIFETIME':           timedelta(days=31),#这个配置文件控制
      
  • 相关阅读:
    原始mvc1
    ssh3,hibernate和maven
    hibernate1
    mybatis和spring一起用
    python怎么生成requirements.txt文件
    selenium.common.exceptions.ElementNotVisibleException: Message: element not interactable (Session info: chrome=74.0.3729.108) (Driver info: chromedriver=2.43.600210
    Android SDK 安装与配置
    pip超时问题解决
    爬取网页数据
    pip安装报错: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy
  • 原文地址:https://www.cnblogs.com/randysun/p/15518273.html
Copyright © 2011-2022 走看看