Global variables in Python and Apache mod_wsgi

I know that frameworks exist, but I'm trying to use wsgi directly to improve my understanding.

I have a wsgi handler, and at the top I declared the variable i = 0 .

In my application(environ, start_response) function application(environ, start_response) I declare global i , and then increment i when I click the button.

As far as I understand, the state of this variable remains as long as the server is running, so all users of the web application see the same i .

If I declare i inside the application function, then the value of i reset to 0 with every request.

I am wondering how you save i between single-user requests, but don't you save it in different user sessions? Thus, one user can create several messages, and i will increase, but if another user visits the web application, they start with i=0 .

And I know that you could store i in the database between messages, but can you just store i in memory between messages?

+4
source share
2 answers

Web applications are usually "shared-nothing". In the context of WSGI, this means that you have no idea how many times your application (and the counter with it) will be created; this choice depends on the WSGI server that acts as your application container.

If you need the concept of user sessions, you must implement it explicitly, usually on top of cookies. If you want perseverance, you need a component that explicitly supports it; which may be a shared database, or it may be copied to your cookie sessions.

+3
source

Add the WSGI session middleware and save this value.

+1
source

Source: https://habr.com/ru/post/1399474/


All Articles