简体   繁体   中英

ImportError - No module named main in GAE

In my Google App Engine app, I'm getting the error

ImportError: No module named main

when going to the URL /foo . All the files in my app are in the parent directory.

Here is my app.yaml :

application: foobar
version: 1
runtime: python27
api_version: 1
threadsafe: no

handlers:

- url: /foo.*
  script: main.application

- url: /
  static_files: index.html

- url: /(.*\.(html|css|js|gif|jpg|png|ico))
  static_files: \1
  upload: .*
  expiration: "1d"

Here is my main.py :

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util

class Handler(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write('Hello world!') 

def main():
    application = webapp.WSGIApplication([('/foo', Handler)],
                                         debug=False)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()

I get the same error when I change main.application to main.py or just main . Why is this error occurring?

Your configuration is OK - only for a small misstep in the main.py : you need an access of the application name from the main module, thus the config is: main.application . This change should do the trick:

application = webapp.WSGIApplication([('/foo', Handler)],
                                     debug=False)
def main():
    util.run_wsgi_app(application)

Don't worry - the application object will not run on creation, nor on import from this module, it will run only on explicit all such as .run_wsgi_app or in google's internal architecture.

Have a look at getting started with python27. You mixing CGI and WSGI. You have to use webapp2 here.

Your WSGI main.py :

import webapp2

class Handler(webapp2.RequestHandler):

    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write('Hello World!')


application = webapp2.WSGIApplication([
    ('/foo', Handler),
], debug=True)

See also this blog post about CGI and WSGI : http://blog.notdot.net/2011/10/Migrating-to-Python-2-7-part-1-Threadsafe

As the documentation says,

Static files cannot be the same as application code files. If a static file path matches a path to a script used in a dynamic handler, the script will not be available to the dynamic handler.

In my case, the problem was that the line

upload: .*

matched all files in my parent directory, including main.py. This meant that main.py was not available to the dynamic handler. The fix was to change this line to only recognize the same files that this rule's URL line recognized:

upload: .*\.(html|css|js|gif|jpg|png|ico)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM