【问题标题】:Global variable that persisted only for the lifetime of the request - Python, Webapp2仅在请求的生命周期内持续存在的全局变量 - Python、Webapp2
【发布时间】:2016-07-12 18:38:59
【问题描述】:

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

x = 0

class MyHandler(webapp2.RequestHandler):

      def get(self):

          global x
          x = x + 1
          print x

每次刷新页面(或连接新用户),计数都会增加。 Python 不会对每个请求启动一个新进程(但我期望它)。我如何处理我想要一个仅在请求的生命周期内持续存在的全局变量的情况?我可以使用实例变量吗?具体如何?

【问题讨论】:

    标签: python google-app-engine wsgi webapp2


    【解决方案1】:

    您看到的行为是预期的。不是为每个请求启动新实例。

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

    有关使用线程本地存储的讨论,请参阅 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      • 2011-10-25
      • 2018-12-14
      • 1970-01-01
      相关资源
      最近更新 更多