I'm starting to learn to use google app engine and, in much of the code 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 themain()
function in the cached environment.
Taken from here: http://code.google.com/appengine/docs/python/runtime.html#App_Caching
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With