Why is the webapp.WSGIApplication instance always defined as a global variable in the Google application engine code?

I am starting to learn how to use the google engine and, in most of the code I came across, they declare an instance of webapp.WSGIApplication as a global variable. This does not seem necessary, since the code works fine when it is locally declared in the main function. I have always been advised to avoid global variables. So is there a good or even not very good reason that it was so?

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.

+6
python google-app-engine global-variables
source share
2 answers

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

However, it is recommended that you select the first option by declaring the application variable outside the main() function.

+7
source share

Perhaps this is due to application caching, and not to replay it every time (for performance):

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

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

+1
source share

All Articles