开发者

Why is an instance of webapp.WSGIApplication always defined as a global variable in google app engine code?

开发者 https://www.devze.com 2023-02-14 15:51 出处:网络
I\'m starting to learn to use google app engine and, in much of the code开发者_如何学C I\'ve come across, they declare the instance of the webapp.WSGIApplication as a global variable.This doesn\'t see

I'm starting to learn to use google app engine and, in much of the code开发者_如何学C I've come across, they declare the instance of the webapp.WSGIApplication as a global variable. This doesn't seem to be necessary, as the code works fine when it is locally declared in the main function. I was always advised that global variables should be avoided. So is there a good, or even not so good, reason that it's done this way?

Example:

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)

Why not do the following, which also works:

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)

This also works in examples with multiple request handlers.


Google App Engine offers a neat feature called App caching.
The first time the main handler is invoked, the full script is evaluated importing the modules and creating the global elements.
If the handler is called after the script has already been evaluated, the app instance simply calls its main() function directly.
The overhead of creating the global elements is payed just the first time and the objects created can be reused by multiple requests saving time and resources.

That said, it is highly recommended to pick the first choice, declaring the application variable outside the main() function.


It's possibly related to the application caching, rather than recreating it each time (for performance):

You can tell App Engine to cache the handler script itself, in addition to imported modules. If the handler script defines a function named main(), then the script and its global environment will be cached like an imported module. The first request for the script on a given web server evaluates the script normally. For subsequent requests, App Engine calls the main() function in the cached environment.

Taken from here: http://code.google.com/appengine/docs/python/runtime.html#App_Caching

0

精彩评论

暂无评论...
验证码 换一张
取 消