在任何传入连接时,无论何时连接新计算机或浏览器并创建新 session cookie,我都想初始化几个 session 变量。如果我这样做:
session["authorized"] = False
session["client_id"] = None
session["client_secret"] = None
session["go_id"] = None
session["test_mode"] = None
在函数装饰器之外,我得到了这个错误:
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem.
如果我使用 app.before_first_request
装饰器,它只会为第一个连接/ session 运行一次初始化,但如果我连接到另一个浏览器,则不会进行初始化。看起来像这样:
@instance.before_first_request
def initialize():
session["authorized"] = False
session["client_id"] = None
session["client_secret"] = None
session["go_id"] = None
session["test_mode"] = None
如果我改为使用 before_request
,则每次请求都会进行初始化,并且变量总是会被覆盖。
我怎样才能初始化每个 session ,但只初始化一次?
最佳答案
试试这个方法对我有用
if not session.get('authorized'):
session['authorized'] = False
if not session.get('client_id'):
session['client_id'] = None
if not session.get('client_secret'):
session['client_secret'] = None
if not session.get('go_idt'):
session['go_id'] = None
if not session.get('test_mode'):
session['test_mode'] = None
关于python - 如何在 Flask 中初始化 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60324369/