简体   繁体   English

如何在 Flask 中初始化会话?

[英]How to initialize a session in Flask?

Upon any incoming connection, so whenever a new computer or a browser connects and a new session cookie is created, I want to initialize a couple of session variables.在任何传入连接上,因此每当新计算机或浏览器连接并创建新会话 cookie 时,我想初始化几个会话变量。 If I do this:如果我这样做:

session["authorized"] = False
session["client_id"] = None
session["client_secret"] = None
session["go_id"] = None
session["test_mode"] = None

outside of a function decorator, I got this error:在函数装饰器之外,我收到了这个错误:

RuntimeError: Working outside of request context.运行时错误:在请求上下文之外工作。
This typically means that you attempted to use functionality that needed an active HTTP request.这通常意味着您尝试使用需要活动 HTTP 请求的功能。 Consult the documentation on testing for information about how to avoid this problem.有关如何避免此问题的信息,请参阅有关测试的文档。

If I use the app.before_first_request decorator, it run the initialization only once for the very first connection/session, but if I connect with another browser, the initialization doesn't happen.如果我使用app.before_first_request装饰器,它只会为第一个连接/会话运行一次初始化,但如果我连接到另一个浏览器,则不会发生初始化。 That looks like this:看起来像这样:

@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

If instead I use before_request , the initialization happens on each request and the variables are always overridden.相反,如果我使用before_request ,则初始化发生在每个请求上,并且变量总是被覆盖。

How can I initialize each single session but just once?我如何初始化每个会话但只初始化一次?

Try this method works for me试试这个方法对我有用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM