How To Use Python Main() Function In Gae (google App Engine)?
Solution 1:
GAE apps are not designed to be standalone apps, a main()
function doesn't make a lot of sense for them.
Basically GAE apps are really just collections of handler code and rules/configurations designed to extend and customize the behaviour of the generic GAE infra/sandbox code so that it behaves your app. You can see that from your backtrace - other code is invoking your handler code (and the stack before reaching your code can be a lot deeper than that).
In your particular case the app
variable must be a global in main.py
to match the script: main.app
config line in the app.yaml
config file. This is what the traceback is about.
As for organizing the code for huge apps, there are other ways of doing it:
splitting the app in multiple modules/services, each with their own
app.yaml
config file. For example: Can a default service/module in a Google App Engine app be a sibling of a non-default one in terms of folder structure?splitting a service/module into multiple "scripts" - primary entry points into the
app.yaml
file similar to yourmain.py
file, each with their ownapp
config` - which really are just mappers between routes and handlers. For example: App Engine throws 404 Not Found for any path but rootsplitting the handlers for one
app
mapper into multiple files, using webapp2's lazy loaded handler technique. Examples:
In an extreme case a main.py
file could contain just the app
variable - that is really the only requirement.
Solution 2:
Seems that the solution was quite simple (it kept eluding me because it hid in plain sight): __name__
is main and not __main__!
In short, the following code utilises a main()
as expected:
# with main()import webapp2
classGetHandler(webapp2.RequestHandler):
defget(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('in GET')
classSetHandler(webapp2.RequestHandler):
defget(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('in SET')
defmain():
global app
app = webapp2.WSGIApplication([
('/get', GetHandler),
('/set', SetHandler),
], debug=True)
# Note that it's 'main' and not '__main__'if __name__ == 'main':
main()
Solution 3:
https://webapp2.readthedocs.io/en/latest/tutorials/quickstart.nogae.html describes how to use GAE apps outside of the GAE environment:
from myapp import app
defmain():
from paste import httpserver
httpserver.serve(app, host='localhost', port='8070')
if __name__ == '__main__':
main()
I did that in order to debug my app using the Pycharm IDE instead of from the dev_appserver command window; it works fine. I compare results with dev_appserver running on port 8080 and the debugger running on 8070.
Post a Comment for "How To Use Python Main() Function In Gae (google App Engine)?"