geeshta
geeshta

Reputation: 61

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. 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. 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. 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.

How can I initialize each single session but just once?

Upvotes: 5

Views: 2968

Answers (1)

willbroad nyirenda
willbroad nyirenda

Reputation: 31

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

Upvotes: 3

Related Questions