How to use Python main() function in GAE (Google App Engine)?

前端 未结 3 550
谎友^
谎友^ 2021-01-16 09:51

I\'d like to use a main() function in my GAE code
(note: the code below is just a minimal demonstration for a much larger program, hence the need for a

3条回答
  •  感动是毒
    2021-01-16 10:47

    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
    
    class GetHandler(webapp2.RequestHandler):
        def get(self):
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.write('in GET')
    
    class SetHandler(webapp2.RequestHandler):
        def get(self):
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.write('in SET')
    
    def main():
        global app
        app = webapp2.WSGIApplication([
            ('/get',    GetHandler),
            ('/set',    SetHandler),
        ], debug=True)
    
    # Note that it's 'main' and not '__main__'
    if __name__ == 'main':
        main()
    

提交回复
热议问题