仅在请求的生命周期内持久化的全局变量 - Python,Webapp2

时间:2016-03-25 01:15:20

标签: python google-app-engine wsgi webapp2

我在Google App Engine的WebApp2应用程序中使用了Python脚本:

x = 0

class MyHandler(webapp2.RequestHandler):

      def get(self):

          global x
          x = x + 1
          print x

每次刷新页面(或连接新用户)时,计数增加更高。 Python不会在每个请求上启动新进程(但我期望它)。我怎么能处理我想要一个仅在请求的生命周期内持久化的全局变量的场景?我可以使用实例变量吗?具体如何?

1 个答案:

答案 0 :(得分:1)

您期待的行为。没有为每个请求启动新实例。

使用请求对象,env对象或线程局部变量来存储您希望在请求的生命周期中可以访问代码的任何位置的信息。 (Environ在每个请求中重新创建,因此它是安全的)。

有关使用线程本地存储的讨论,请参阅Is threading.local() a safe way to store variables for a single request in Google AppEngine?

以下是存储本地请求对象以存储请求生命周期内的特定信息的示例。所有这些代码都必须在您的处理程序中。所有部分都记录在webapp2文档中。顺便说一下,我不使用webapp2,所以这还没有经过测试。 (我使用金字塔/ bobo和此模型执行请求级别缓存)。

类MyHandler(webapp2.RequestHandler):

  def get(self):
      req = webapp2.get_request()   
      # you have request in self, however this is to show how you get a 
      # request object anywhere in your code.


      key = "Some Key"

      if req:
            # getting some store value from the environ of request (See WebOb docs)
            someval = req.environ.get(key,None)
            if someval :
                # do something

      # and setting
      if req:
            req.environ[key] = 'some value'

这样做有一个限制,即environ [' key']值必须是一个字符串。

阅读Webob文档,了解如何在请求对象中存储任意值。 http://docs.webob.org/en/stable/reference.html#ad-hoc-attributes -

req.environ['webob.adhoc_attrs']
{'some_attr': 'blah blah blah'}

此外,如果您已阅读webapp2请求对象文档,则可以使用一个注册表来存储信息 - http://webapp-improved.appspot.com/api/webapp2.html#webapp2.Request

请注意,您在请求处理程序之外定义的任何变量基本上都是缓存的,可用于实例生存期。这是你出错的地方。

要了解应用级缓存的工作方式/原因 - 以及为什么您的第一次尝试没有做您想做的事情,请查看https://cloud.google.com/appengine/docs/python/requests#Python_App_caching

相关问题