当前位置: 首页 > 工具软件 > flask-session > 使用案例 >

python flask-session 结合redis实现session共享

黄昊
2023-12-01
import os
from flask import *
from flask_cors import CORS
from flask_login import (LoginManager, current_user, login_required,
                         login_user, logout_user)
from flask_moment import Moment

app = Flask(__name__)
app.config['BUNDLE_ERRORS'] = True

import os
from flask import Flask, session, request
from flask_session import Session
from redis import Redis

app = Flask(__name__)




app.config['SESSION_TYPE'] = 'redis'   #session存储格式为redis
app.config['SESSION_REDIS'] = Redis(    #redis的服务器参数
    host=config.redist_host,                #服务器地址
    port=config.redis_port,
    password=config.redis_password)                           #服务器端口

app.config['SESSION_USE_SIGNER'] = False   #是否强制加盐,混淆session
app.config['SECRET_KEY'] = b'1'  #如果加盐,那么必须设置的安全码,盐
app.config['SESSION_PERMANENT'] = True
app.config['PERMANENT_SESSION_LIFETIME'] = 3600   #session长期有效,则设定session生命周期,整数秒,默认大概不到3小时。
Session(app)


@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        username = request.form.get('username', None)
        password = request.form.get('password', None)
        remember_me = request.form.get('remember_me', False)
        next = 'uservm'
        session['_user_id']=username 

用户验证方式

def login_requires(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        cookies = request.cookies.get('session')
        if cookies == None:
            return redirect(url_for('login'))
        print(('_user_id' in session))
        # if not RedisDB().checkkey_exits(f"session:{cookies}") or ('_user_id' not in session):
        #     return redirect(url_for('login'))
        if not RedisDB().checkkey_exits(f"session:{cookies}") or ('_user_id' not in session):
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

redis

import redis
from db_connection import config
class RedisDB:
    def __init__(self):
        self.pool=redis.ConnectionPool(host=config.redist_host,port=config.redis_port,decode_responses=True,db=0,password=config.redis_password)
        self.r=redis.Redis(connection_pool=self.pool,decode_responses=True)
    def increase(self,name,value):
        self.r.incr(name,amount=int(value))

    def decrease(self,name,value):
        self.r.decr(name,amount=int(value))

    def getvalue(self,name,decodes=False):
        if self.r.exists(name):
            if decodes:
                with self.r.responses_as_bytes:
                    return self.r.get(name)
            else:
                return self.r.get(name)
        return 0

    def clone(self,bucketname,teamname,username):
        self.increase(bucketname + '-' + teamname,1)
        self.increase(username,1)

    def destory(self,bucketname,teamname,username):
        self.decrease(bucketname + '-' + teamname,1)
        self.decrease(username,1)

    def applylonguse(self,bucketname,teamname,username):
        self.increase(bucketname + '-' + teamname + " 6 months",1)
        self.increase(username + " 6 months",1)
    
    def destorylonguse(self,bucketname,teamname,username):
        self.decrease(bucketname + '-' + teamname + " 6 months",1)
        self.decrease(username + " 6 months",1)


    def deletelist(self,vm_uuid):
        self.r.sadd('deletelist',vm_uuid)

    def ifdeletefromVmPortal(self,vm_uuid):
        return self.r.sismember('deletelist',vm_uuid)

    def removedelete(self,vm_uuid):
        self.r.srem('deletelist',vm_uuid)

# template limit count
    def increasehkey(self,template_id,template_child_id):

        self.r.hincrby(template_id,template_child_id,1)

    def decreasehkey(self,template_id,template_child_id):

        self.r.hincrby(template_id,template_child_id,-1)


    def gethkey(self,template_id,template_child_id):
        
        return self.r.hget(template_id,template_child_id)

    def getall(self,template_id):
        if self.r.exists(template_id):
            return self.r.hgetall(template_id)
        else:
            return None
        
    def checkkey_exits(self,keys):
        return self.r.exists(keys)
    
    def logout(self,key):
        self.r.delete(key)

注意secret_key要设置成定值

http://stackoverflow.com/questions/30370500/sessions-always-empty-with-flask-heroku

secret_key设置成os.urandom(24)的话,它的值就会变化,而一旦发生变化,原来的cookie中的token就不能被新的secret_key验证,于是cookie就失效了,相应的session存的内容也就没了,所以会再次提示用户登录。因此以后secret_key最好设置成一个固定的字符串!

 类似资料: