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 ...
 
随机推荐
- ASP.NET CS文件中输出JavaScript脚本
			
ClientScript.RegisterStartupScript:http://msdn.microsoft.com/zh-cn/library/system.web.ui.clientscrip ...
 - 让我们共同构筑物联网起飞的平台:物联网操作系统Hello China寻求应用合作伙伴
			
经过几天的努力,终于把Hello China V1.76版的内核移植到基于Cortex-M3内核的STM32 chipset上.因为还希望进一步写一个USART驱动程序,因此详细的移植文档,预计一周之 ...
 - stm32之GPIO(二)
			
输入上拉:当IO口作为输入时,比如按键输入,而按键是与地连接,按下时为低电平,则没按下时该IO口应为高电平,上拉即是该IO口通过一个电阻与电源相连,则没按下时为高电平,按下即为低电平. 输入下拉:同理 ...
 - 修改字符串 ToCharArray()
			
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
 - ViewPager实现广告自动轮播核心代码(Handler+Thread)
			
ViewPager数据源是4个线性布局,每个布局里面充满一张高度固定.宽度充满父布局的图片.有4个小圆点跟随ViewPager滑动.轮播原本我是用Timer+TimerTask的,但是问题颇多,很是郁 ...
 - atlas z 轴
			
问题源自一个帖子,因为上传的图比较多,就另开了这个贴写下自己的试验结果,原帖在下面链接中 http://game.ceeger.com/forum/read.php?tid=8911#info NGU ...
 - SUP (SAP Mobile SDK 2.2) 连接 Sybase SQL Anywhere sample 数据库
			
安装了 SAP Mobile SDK 2.2 后发现,这个版本没有自带Sybase SQL Anywhere 数据库. 解决办法: 1. 免费下载 SQL Anywhere Develope ...
 - 九度OnlineJudge之1023:EXCEL排序
			
题目描述: Excel可以对一组纪录按任意指定列排序.现请你编写程序实现类似功能. 对每个测试用例,首先输出1行“Case i:”,其中 i 是测试用例的编号(从1开始).随后在 N ...
 - hdu 2757 Ocean Currents(优先队列+bfs)
			
小伙伴们真心被这道题惊呆了!刚开始是读题,题目都把小伙伴惊呆了,题目都读不懂! 在前面猴子小伙伴的帮助下,理解了一点点,又偷偷的在纸上写写画画,明白了题意! 后来,你懂的,果断拿下!在拿下的过程也经过 ...
 - sencha touch(7)——list组件
			
1.list组件是一个很强大的组件.用于以一览表的形式或者列表的形式展示应用程序中的大量的数据.该组件使用XTemplate模版来显示数据,同时与数据仓库进行绑定.所以当数据仓库中的数据发生变化的时候 ...