Project structure for Google App Engine

后端 未结 6 828
走了就别回头了
走了就别回头了 2020-12-12 09:06

I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time bu

6条回答
  •  Happy的楠姐
    2020-12-12 09:47

    First, I would suggest you have a look at "Rapid Development with Python, Django, and Google App Engine"

    GvR describes a general/standard project layout on page 10 of his slide presentation.

    Here I'll post a slightly modified version of the layout/structure from that page. I pretty much follow this pattern myself. You also mentioned you had trouble with packages. Just make sure each of your sub folders has an __init__.py file. It's ok if its empty.

    Boilerplate files

    • These hardly vary between projects
    • app.yaml: direct all non-static requests to main.py
    • main.py: initialize app and send it all requests

    Project lay-out

    • static/*: static files; served directly by App Engine
    • myapp/*.py: app-specific python code
      • views.py, models.py, tests.py, __init__.py, and more
    • templates/*.html: templates (or myapp/templates/*.html)

    Here are some code examples that may help as well:

    main.py

    import wsgiref.handlers
    
    from google.appengine.ext import webapp
    from myapp.views import *
    
    application = webapp.WSGIApplication([
      ('/', IndexHandler),
      ('/foo', FooHandler)
    ], debug=True)
    
    def main():
      wsgiref.handlers.CGIHandler().run(application)
    

    myapp/views.py

    import os
    import datetime
    import logging
    import time
    
    from google.appengine.api import urlfetch
    from google.appengine.ext.webapp import template
    from google.appengine.api import users
    from google.appengine.ext import webapp
    from models import *
    
    class IndexHandler(webapp.RequestHandler):
      def get(self):
        date = "foo"
        # Do some processing        
        template_values = {'data': data }
        path = os.path.join(os.path.dirname(__file__) + '/../templates/', 'main.html')
        self.response.out.write(template.render(path, template_values))
    
    class FooHandler(webapp.RequestHandler):
      def get(self):
        #logging.debug("start of handler")
    

    myapp/models.py

    from google.appengine.ext import db
    
    class SampleModel(db.Model):
    

    I think this layout works great for new and relatively small to medium projects. For larger projects I would suggest breaking up the views and models to have their own sub-folders with something like:

    Project lay-out

    • static/: static files; served directly by App Engine
      • js/*.js
      • images/*.gif|png|jpg
      • css/*.css
    • myapp/: app structure
      • models/*.py
      • views/*.py
      • tests/*.py
      • templates/*.html: templates

提交回复
热议问题