Server-side Sessions with Redis | Flask (A Python Microframework)
Server-side Sessions with Redis | Flask (A Python Microframework)
Server-side Sessions with Redis
By Armin Ronacher filed in Sessions
If you need to store a lot of session data it makes sense to move the data from the cookie to the server. In that case you might want to use redis as the storage backend for the actual session data.
The following code implements a session backend using redis. It allows you to either pass in a redis client or will connect to the redis instance on localhost. All the keys are prefixed with a specified prefix which defaults to
session:.import pickle
from datetime import timedelta
from uuid import uuid4
from redis import Redis
from werkzeug.datastructures import CallbackDict
from flask.sessions import SessionInterface, SessionMixin class RedisSession(CallbackDict, SessionMixin): def __init__(self, initial=None, sid=None, new=False):
def on_update(self):
self.modified = True
CallbackDict.__init__(self, initial, on_update)
self.sid = sid
self.new = new
self.modified = False class RedisSessionInterface(SessionInterface):
serializer = pickle
session_class = RedisSession def __init__(self, redis=None, prefix='session:'):
if redis is None:
redis = Redis()
self.redis = redis
self.prefix = prefix def generate_sid(self):
return str(uuid4()) def get_redis_expiration_time(self, app, session):
if session.permanent:
return app.permanent_session_lifetime
return timedelta(days=1) def open_session(self, app, request):
sid = request.cookies.get(app.session_cookie_name)
if not sid:
sid = self.generate_sid()
return self.session_class(sid=sid, new=True)
val = self.redis.get(self.prefix + sid)
if val is not None:
data = self.serializer.loads(val)
return self.session_class(data, sid=sid)
return self.session_class(sid=sid, new=True) def save_session(self, app, session, response):
domain = self.get_cookie_domain(app)
if not session:
self.redis.delete(self.prefix + session.sid)
if session.modified:
response.delete_cookie(app.session_cookie_name,
domain=domain)
return
redis_exp = self.get_redis_expiration_time(app, session)
cookie_exp = self.get_expiration_time(app, session)
val = self.serializer.dumps(dict(session))
self.redis.setex(self.prefix + session.sid, val,
int(redis_exp.total_seconds()))
response.set_cookie(app.session_cookie_name, session.sid,
expires=cookie_exp, httponly=True,
domain=domain)Here is how to enable it:
app = Flask(__name__)
app.session_interface = RedisSessionInterface()If you get an attribute error that
total_secondsis missing it means you're using a version of Python older than 2.7. In this case you can use this function as a replacement for thetotal_secondsmethod:def total_seconds(td):
return td.days * 60 * 60 * 24 + td.secondsThis snippet by Armin Ronacher can be used freely for anything you like. Consider it public domain.
Server-side Sessions with Redis | Flask (A Python Microframework)的更多相关文章
- 教程 Redis+ flask+vue 在线聊天
知识点 基于 Server-Sent Event 工作方式,Web 即时通信 Redis 包 发布订阅功能的使用 flask 快速入门,常用对象实例方法函数 Vuejs 列表页面自动渲染 效果图 代码 ...
- 4.使用Redis+Flask维护动态代理池
1.为什么使用代理池 许多⽹网站有专⻔门的反爬⾍虫措施,可能遇到封IP等问题. 互联⽹网上公开了了⼤大量量免费代理理,利利⽤用好资源. 通过定时的检测维护同样可以得到多个可⽤用代理理. 2.代理池的要 ...
- 通过uwsgi+nginx启动flask的python web程序
通过uwsgi+nginx启动flask的python web程序 一般我们启动python web程序的时候都是通过python直接启动主文件,测试的时候是可以的,当访问量大的时候就会出问题pyth ...
- python三大web框架Django,Flask,Flask,Python几种主流框架,13个Python web框架比较,2018年Python web五大主流框架
Python几种主流框架 从GitHub中整理出的15个最受欢迎的Python开源框架.这些框架包括事件I/O,OLAP,Web开发,高性能网络通信,测试,爬虫等. Django: Python We ...
- Redis安装即python使用
一:简介 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合).zset(sorted ...
- redis 原生操作 & python操作redis
一.基本介绍 1.简介 Redis是由意大利人Salvatore Sanfilippo(网名:antirez)开发的一款内存高速缓存数据库.Redis全称为:Remote Dictionary Ser ...
- 令人抓狂的redis和rediscluster Python驱动包的安装
本文环境:centos 7,Python3编译安装成功,包括pip3,然后需要安装redis相关的Python3驱动包,本的redis指redis包而非redis数据库,rediscluster类似. ...
- C# 启动 Flask for Python
概览 最近有个需求是通过c#代码来启动 python 脚本.嘿~嘿!!! 突发奇想~~既然可以启动 python 脚本,那也能启动 flask,于是开始着手操作. 先看gif图 准备 因为使用的是.N ...
- flask实现python方法转换服务
一.flask安装 pip install flask 二.flask简介: flask是一个web框架,可以通过提供的装饰器@server.route()将普通函数转换为服务 flask是一个web ...
随机推荐
- (IOS)Apple 证书相关
1.私钥 本地钥匙串程序创建<证书请求文件>(.certSigningRequest),用其向苹果申请下载<证书文件>/<私钥>(.cer),并安装到钥匙串: 团队 ...
- Web调试利器fiddler使用
fiddler官网:http://fiddler2.com/ http://wenku.baidu.com/view/053e79d776a20029bd642dc1 http://www.cnblo ...
- 汇总:Linux下10款即时通讯客户端,skype
aMSN 是一款功能强大的MSN(WLM)的客户端,支持皮肤.插件.系统托盘图标.摄像头.多帐号登录.离线信息等. Pidgin 不用说了,是GNOME下的IM客户端,支持AIM, Google Ta ...
- Java面试题之三
十一.谈谈final,finally,finalize的区别? 1.final:是修饰符,是一个关键字.修饰变量,如果是基本类型表示该变量的值不能修改:如果是引用类型表示该变量不能指向别的对象:修饰类 ...
- OpenStack导入镜像后Launch不起来的几个问题
Dashboard上显示state为error 没有其他报错 用nova list找到虚拟机的id 然后nova show,可以得到fault详细信息 也可以查看下面两个log /var/log/no ...
- java 简单的数据增删该查
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sq ...
- c++, 虚基派生 : 共同基类产生的二义性的解决办法
虚基派生 //虚继承 #include <iostream> using namespace std; #include <string> //---------------- ...
- Python相关项目和技术
下面的项目是<Learn PYTHON the hard way>里面的,以后可能会补充: 1.Django,创建web程序的框架:https://www.djangoproject.co ...
- [Swust OJ 234]--IrreducibleNumber(题意太坑)
题目链接:http://acm.swust.edu.cn/problem/0234/ Time limit(ms): 1000 Memory limit(kb): 65535 Descriptio ...
- java 如何自定义异常 用代码展示 真心靠谱
先建两个自定义的异常类 ChushufuException类 class ChushufuException extends Exception { public ChushufuException( ...