简单的服务器端Flask会话变量 [英] Simple server-side Flask session variable
问题描述
在Flask中拥有服务器端会话变量的最简单方法是什么?
What is the easiest way to have a server-side session variable in Flask?
变量值:
- 一个简单的字符串
- 客户端(浏览器)不可见
- 不能持久存储到数据库中-会话消失后就消失了
有一个内置的Flask会话,但是它将会话数据发送到客户端:
There is a built-in Flask session, but it sends the session data to the client:
session["secret"] = "I can see you"
数据是Base64编码的,并以加密签名的cookie发送,但是在客户端上读取仍然很简单.
The data is Base64 encoded and sent in a cryptographically signed cookie, but it is still trivial to read on the client.
在许多框架中,创建服务器端会话变量是一种形式,例如:
In many frameworks, creating a server-side session variable is a one-liner, such as:
session.secret = "You can't see this"
到目前为止,我发现的Flask解决方案非常麻烦,并且适合处理大量数据.有一个简单的轻量级解决方案吗?
The Flask solutions I have found so far are pretty cumbersome and geared towards handling large chunks of data. Is there a simple lightweight solution?
推荐答案
我认为 Flask-Session 扩展程序就是您想要的.
I think the Flask-Session extension is what you are looking for.
Flask-Session是Flask的扩展,它为您的应用程序添加了对服务器端会话的支持.
Flask-Session is an extension for Flask that adds support for Server-side Session to your application.
从链接的网站上:
from flask import Flask, session
from flask_session import Session # new style
# from flask.ext.session import Session # old style
app = Flask(__name__)
# Check Configuration section for more details
SESSION_TYPE = 'redis'
app.config.from_object(__name__)
Session(app)
@app.route('/set/')
def set():
session['key'] = 'value'
return 'ok'
@app.route('/get/')
def get():
return session.get('key', 'not set')
这篇关于简单的服务器端Flask会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!