Global variables in Python and Apache mod_wsgi

蓝咒 提交于 2019-12-22 08:17:53

问题


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?


回答1:


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.




回答2:


Add WSGI session middleware and store the value these.



来源:https://stackoverflow.com/questions/9541301/global-variables-in-python-and-apache-mod-wsgi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!