flask-session组件:将cookie中的session值存放至redis

1、安装

pip install flask-session

2、使用

方式一:

import redis

pool = redis.ConnectionPool(host="10.0.0.10", password="azn950626", port=6379)
single_pool = redis.Redis(connection_pool=pool)

redis_pool.py

from flask import Flask, session
from flask_session import RedisSessionInterface

app = Flask(__name__)
app.session_interface = RedisSessionInterface(redis=redis_pool.single_pool, key_prefix="yoyo")

@student.route(‘/student/<regex("\d+"):nid>‘)
def list_student(nid):
    session[‘username‘] = ‘aike‘
    return render_template("student.html")

方式二:

import redis

pool = redis.ConnectionPool(host="10.0.0.10", password="azn950626", port=6379)
single_pool = redis.Redis(connection_pool=pool)

redis_pool.py

from .utils import regex, redis_pool
from flask.ext.session import Session


app.config[‘SESSION_TYPE‘] = ‘redis‘
app.config[‘SESSION_REDIS‘] = redis_pool.single_pool
Session(app)

问题1:如何关闭浏览器,cookie则失效: permanent=False

app.session_interface = RedisSessionInterface(redis=redis_pool.single_pool, key_prefix="yoyo", permanent=False)

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

    默认31天,在默认配置文件中修改

app = Flask(__name__)
    app.default_config
"PERMANENT_SESSION_LIFETIME": timedelta(days=31),  # session在浏览器超时时间

相关推荐