我开始学习使用Google App Engine,并且在我遇到的许多代码中,他们都将webapp.WSGIApplication的实例声明为全局变量。这似乎不是必需的,因为当在主函数中本地声明该代码时,该代码可以正常工作。
始终建议我避免使用全局变量。那么,是否有这样做的良好或什至不是很好的理由呢?

例子:

class Guestbook(webapp.RequestHandler):
  def post(self):
    greeting = Greeting()

    if users.get_current_user():
      greeting.author = users.get_current_user()

    greeting.content = self.request.get('content')
    greeting.put()
    self.redirect('/')

application = webapp.WSGIApplication([  ('/', MainPage),  ('/sign', Guestbook)], debug=True)

def main():
  wsgiref.handlers.CGIHandler().run(application)

为什么不执行以下操作,该方法也有效:
class Guestbook(webapp.RequestHandler):
  def post(self):
    greeting = Greeting()

    if users.get_current_user():
      greeting.author = users.get_current_user()

    greeting.content = self.request.get('content')
    greeting.put()
    self.redirect('/')

def main():
  application = webapp.WSGIApplication([  ('/', MainPage),  ('/sign', Guestbook)], debug=True)
  wsgiref.handlers.CGIHandler().run(application)

这在具有多个请求处理程序的示例中也适用。

最佳答案

Google App Engine提供了一个名为App caching的简洁功能。
第一次调用主处理程序时,将评估完整脚本,以导入模块并创建全局元素。
如果在评估脚本后调用了该处理程序,则该应用程序实例将直接直接调用其main()函数。
创建全局元素的开销只是第一次支付,创建的对象可以被多个请求重用,从而节省了时间和资源。

也就是说,强烈建议您选择第一个选项,在application函数之外声明main()变量。

关于python - 为什么在Google App Engine代码中始终将webapp.WSGIApplication实例定义为全局变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5172694/

10-12 12:33
查看更多