title: Understanding global object persistence in Python WSGI apps
body: <p>Consider the following code in my WebApp2 application in Google App Engine:</p>
  
  <pre><code>count = 0
  
  class MyHandler(webapp2.RequestHandler):
  
      def get(self):
  
          global count
          count = count + 1
          print count
  </code></pre>
  
  <p>With each refresh of the page, the count increments higher.</p>
  
  <p>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...</p>
  
  <p>Assuming the above is correct (If not, please correct me) ...</p>
  
  <ol>
  <li>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?</li>
  <li>Is there some sort of technique to reset all variables, or to force a re-instantiation of the environment?</li>
  <li>Does the global environment persist indefinitely, or does it reset itself at some point?</li>
  <li>Is any of this GAE specific, or does wsgi global persistance work the same in any server scenario?</li>
  </ol>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Here's an attempt using threadlocal:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>These also increment across requests</p>