Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

python - Does flask session variable maintain state across threads?

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's session as completely independent objects), but it is somehow synchronized across threads by flask (presumably with some process-global in-memory data structure). In that case, flask could make all modifications to session 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the very next sentence after the one you quoted:

The way Flask does this is by using a signed cookie.

Flask stores the information in the cookie before sending the response, and reads it back at the beginning of the next request.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...