Consider the following code in my WebApp2 application in Google App Engine:
count = 0
class MyHandler(webapp2.RequestHandler):
def get(self):
global count
count = count + 1
print count
With each refresh of the page, the count increments higher.
I'm coming from the PHP world where every request was a new global environment. What I understand to be happening here is, because I'm using the wsgi configuration for WebApp2, Python does not kick off a new process on each request. If I was using a cgi configuration, on the other hand, the global environment would re-instantiate each time, like PHP...
Assuming the above is correct (If not, please correct me) ...
- How could I handle scenarios where I'd want a global variable that persisted only for the lifetime of the request? I could put an instance variable in the RequestHandler class, but what about things like utility modules that I import that use global vars for things like storing a message object?
- Is there some sort of technique to reset all variables, or to force a re-instantiation of the environment?
- Does the global environment persist indefinitely, or does it reset itself at some point?
- Is any of this GAE specific, or does wsgi global persistance work the same in any server scenario?
EDIT:
Here's an attempt using threadlocal:
count = 0
mydata = threading.local()
mydata.count = 0
class MyHandler(webapp2.RequestHandler):
def get(self):
global count
count = count + 1
print count
mydata.count = mydata.count + 1
print mydata.count
These also increment across requests