Python + Flask - Removing key from session too fas

2020-08-03 04:28发布

问题:

I have and API service that make this:

session[parent].pop(child)

But, when I call this service more than one time and at the same time in Browser, this seems too fast for Flask (or Python, or I don't know). Just one 'child' is removed. I tried to use

del session[parent][child]

but the problem was the same. I can get a list of values in my API Service to resolve that, but, I want to understand why this is happening.

I don't know if it is a Flask problem, a Python problem, a 'Web Stuff' problem...

回答1:

It's a 'Web Stuff' problem.

What happens is that the browser stores the last version it received. But if it receives responses out of order, or you abort a request before it is completed, the browser won't be storing that version.

Flask stores the data for session entirely in a cookie. There is nothing stored on the server side other than the server-side secret used to encrypt and decrypt the contents.

A response with that cookie is sent to the browser, and the browser stores the cookie. This is an entirely opaque piece of data to the browser, it cannot do anything with it as it is compressed and cryptographically signed.

The browser will then send that cookie as is back to the Flask server every time a request is made. If the response to that request contains a new version of the cookie, then that'll be stored in the browser cookie storage. Any new request started after storing will then use the new cookie.

If however, you start a request before a response has been fully processed, or did not complete handling the response, then an older cookie could be used and your server decodes that older version with the changes not made.



回答2:

Just set session.modified = True each time you modify your session. This tells flask to update session after request.