Search code examples
pythongoogle-app-enginepython-2.7webapp2

how to organise files with python27 app engine webapp2 framework


I've gone through the getting started tut for python27 and app engine: https://developers.google.com/appengine/docs/python/gettingstartedpython27/

By the end of the tut, all the the classes are in the same file (helloworld.py) and you and you configure the router to point a url path to a class at the bottom of the file:

 app = webapp2.WSGIApplication([('/', MainPage),
                           ('/sign', Guestbook)],
                          debug=True)

What the tut did not cover is how do I orginise my classes / files as my app grows. For example, would I put MainPage in a separate file and then call 'import MainPage' in the helloworld.py file and add the route to the WSGIApplication? Is there anything more automated than this? What should I call the MainPage file and where should I store it?


Solution

  • Preferable to importing all of your handlers at app-startup is to take advantage of webapp2's lazy handler loading which loads modules/packages as needed.
    So you have a couple of options:

    Option 1, Handlers in a module
    Place MainPage in another file (module) at the same level as your helloworld.py file:

    /my_gae_app
        app.yaml
        helloworld.py
        handlers.py
    

    And in your routing (in helloworld.py) you would do:

    app = webapp2.WSGIApplication([('/', 'handlers.MainPage'),
                                   ('/sign', 'handlers.Guestbook')],
                                  debug=True)
    

    Option 2, Handlers in a package; perhaps consider as your app gets larger
    As your app gets larger you may wish to create a package in which to place your handlers:

    /my_gae_app
        /handlers
            __init__.py
            guestbook.py
            main.py
        app.yaml
        helloworld.py
    

    Routes (in helloworld.py):

    app = webapp2.WSGIApplication([('/', 'handlers.main.MainPage'),
                                   ('/sign', 'handlers.guestbook.Guestbook')],
                                  debug=True)