John Thompson
John Thompson

Reputation: 1684

Global variables in Python and Apache mod_wsgi

I know there are frameworks that exist, but I am trying to use wsgi directly to improve my own understanding.

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

In my application(environ, start_response) function, I declare global i, then I increment i whenever a button is pressed.

It is my understanding that the state of this variable is preserved as long as the server is running, so all users of the web app see the same i.

If I declare i inside the application function, then the value of i resets to 0 any time a request is made.

I'm wondering, how do you preserve i between a single user's requests, but not have it preserved across different users' sessions? So, a single user can make multiple posts, and i will increment, but if another user visits the web app, they start with i=0.

And I know you could store i in a database between posts, but is it possible to just keep i in memory between posts?

Upvotes: 4

Views: 3893

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798636

Add WSGI session middleware and store the value these.

Upvotes: 1

Tobu
Tobu

Reputation: 25426

Web-apps are generally “shared-nothing”. In the context of WSGI, that means you have no idea how many times your application (and the counter with it) will be instantiated; that choice is up to the WSGI server which acts as your app's container.

If you want some notion of user sessions, you have to implement it explicitly, typically on top of cookies. If you want persistence, you need a component that explicitly supports it; that can be a shared database, or it can piggy-back on your cookie sessions.

Upvotes: 3

Related Questions