According to the docs:
A session basically makes it possible to remember information from one request to another.
But elsewhere, the docs say that session
is local to a thread. So if flask
is used in a multithreaded environment (say, app.run(threaded=True)
), how can it fulfill this promise?
I only see two alternatives:
flask
somehow ensures that the same user session is always serviced by the same thread (which seems horrible because a single user browsing in two tabs would have to wait for his first request to finish before his second request is handled)session
is completely useless if I allow threads, and I need to store session-specific information in a database (which seems rather unexpected and isn't mentioned in the docs)
Am I missing something?
Edit: I guess another alternative is:
session
itself is a thread-local variable from python perspective (i.e., python sees each thread'ssession
as completely independent objects), but it is somehow synchronized across threads byflask
(presumably with some process-global in-memory data structure). In that case,flask
could make all modifications tosession
atomic (using some inter-thread synchronization mechanism).
Update: based on @Daniel Roseman answer, my last guess was correct, except flask doesn't do it itself but rather asks the user agent to store / retrieve persistent state (and thus, the state is not per flask process or per flask application but rather per whatever collection of requests the user agent happens to persist the state over - what one might call user session).
See Question&Answers more detail:os