7

Scenario:

  • Major web app w. Python+Flask
  • Flask login and Flask.session for basic session variables (user-id and session-id)

Flask.session and limitations? (Cookies)

  • Cookie based and basically persist only at the client side.

  • For some session variables that will be regularly read (ie, user permissions, custom application config) it feels awkward to carry all that info around in a cookie, at every single page request and response.

Database is too much?

  • Since the session can be identified at the server side by introducing unique session id at login, some server-side session variable management can be used. Reading this data at the server side from a database also feels like unnecessary overhead.

Question

  • What is the most efficient way to handle the session variables at the server side?

Perhaps that could be a memory-based solution, but I am worried that different Flask app requests could be executed at different threads that would not share the memory-stored session data, or cause conflicts in case of simultaneous reading-writing.

  • I am looking for advice and best practice for planning the basic level architecture.
4

2 回答 2

1

您的直觉是正确的,这可能不是这样做的方法。

会话数据应该只是临时信息,不会太麻烦而无法丢失和重新创建。例如,用户只需再次登录即可恢复它。

配置数据或服务器上必需的并且必须在注销后幸存的任何其他内容不是会话的一部分,应该存储在数据库中。

现在,如果您确实需要轻松地将这些信息保留在客户端,并且如果丢失也不是什么大问题,那么请使用会话 cookie 来记录登录/退出状态,并使用具有较长生命周期的永久 cookie 来保持其余部分配置信息。

如果信息的大小太大,那么我能想到的唯一选择是将登录/注销状态以外的数据存储在数据库中。

于 2014-02-22T04:29:31.633 回答
0

烧瓶缓存

您需要的是Flask-Caching的服务器端缓存包。

一个简单的设置:

from flask import Flask
from flask_caching import Cache

app = Flask(__name__)
app.config['CACHE_TYPE'] = 'SimpleCache' 
cache = Cache(app)

然后显式使用缓存变量

@app.route('/')
def load():
    cache.set("foo", foo)
    bar = cache.get("foo")

Flask-Caching 中还有更多内容,这是 Flask推荐的方法。如果从这里使用 带有 gunicorn 的多线程服务器,您最好使用 ['CACHE_TYPE'] = 'FileSystemCache'

于 2021-11-09T18:39:32.480 回答