ModuleNotFoundError-尝试启动服务时没有名为“ main”的模块

时间:2018-09-18 23:01:21

标签: python django google-app-engine google-cloud-platform gunicorn

上下文:

  • 我使用Python 3.7创建了Django应用程序。
  • 我(正在尝试)使用第二代Google App Engine标准环境。

通过python manage.py runserver运行我的应用程序时,它的运行无懈可击。但是,当我尝试将其部署到Google App Engine时,突然停顿了。

Traceback (most recent call last):
  File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
    worker.init_process()
  File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process
    self.load_wsgi()
  File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
    self.wsgi = self.app.wsgi()
  File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
    self.callable = self.load()
  File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
    return self.load_wsgiapp()
  File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
    return util.import_app(self.app_uri)
  File "/tmp/tmphgUsp3/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
    __import__(module)
ModuleNotFoundError: No module named 'main'

我经历了很多线程,但找不到问题。 (作为参考,dev_appserver.py模拟器会产生相同的问题,这是一件好事。)

以下是我的app.yaml

runtime: python37
env: standard

handlers:
- url: /static
  static_dir: static/
- url: .*
  script: demosite.wsgi.main

我的wsgi.py文件位于以下路径中:demosite/wsgi.py,其内容如下所示:

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demosite.settings')

main = get_wsgi_application()

我的settings.py文件:

import os

class AppSettings(object):
    GoogleCloudProject = os.getenv('GOOGLE_CLOUD_PROJECT')

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = 'say what?'

DEBUG = True

ALLOWED_HOSTS = [
    '*'
]


INSTALLED_APPS = [
    'anchor.apps.AnchorConfig',
    'crispy_forms',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'demosite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'demosite.wsgi.main'

try:
    import MySQLdb
except ImportError:
    import pymysql
    pymysql.install_as_MySQLdb()


if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'):
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'webapp',
            'USER': 'aasdeytst',
            'PASSWORD': 'asdasygetasfasdfasd.',
            'HOST': 'asdgiuasfivaasd',
            'PORT': '3306'
        }
    }
else:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'webapp',
            'USER': 'awthdsfhfdhdf',
            'PASSWORD': 'asdasdasdagwdatwt',
            'HOST': 'localhost',
            'PORT': '3306'
        }
    }

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

ANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_ROOT = 'static'
STATIC_URL = '/static/'

CRISPY_TEMPLATE_PACK = 'bootstrap4'

LOGIN_REDIRECT_URL = 'index'
LOGIN_URL = 'login'

SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_COOKIE_AGE = 1800

我想念什么,我做错了什么?我花了将近4个小时的时间试图解决这个问题,但无济于事。

4 个答案:

答案 0 :(得分:8)

默认情况下,App Engine在名为app的文件中查找main.py变量。您有两种选择:将WSGI应用程序放置在App Engine期望的位置,或定义自定义入口点:

将您的WSGI应用放在App Engine希望的位置:

您可以创建一个名为main.py的文件,该文件具有一个app变量,该变量只需从正确的位置导入并作为别名即可。

from demosite.wsgi import main as app

添加自定义入口点:

来自https://cloud.google.com/appengine/docs/standard/python3/config/appref

  

entrypoint:可选。应用启动时执行的命令。为了使您的应用程序接收HTTP请求,entrypoint应该包含一个命令,该命令启动一个Web服务器,该服务器侦听PORT环境变量指定的端口。如果您未指定entrypoint,则App Engine将配置并启动Gunicorn网络服务器。

默认情况下是这样:

entrypoint: gunicorn -b :$PORT main:app

您将需要以下内容:

entrypoint: gunicorn -b :$PORT demosite.wsgi:main

有关应用程序启动的更多详细信息,请参见此处:https://cloud.google.com/appengine/docs/standard/python3/runtime#application_startup

答案 1 :(得分:1)

只需将您的主Python应用程序(对我来说就是app.py)重命名为main.py。 Google Cloud需要main.py才能开始该过程。

答案 2 :(得分:0)

添加:

main.py必须位于应用程序的根目录中,其中app.yaml在其中。

内容也可以是:

   from mysite.wsgi import application

   # App Engine by default looks for a main.py file at the root of the app
   # directory with a WSGI-compatible object called app.
   # This file imports the WSGI-compatible object of your Django app,
   # application from mysite/wsgi.py and renames it app so it is discoverable by
   # App Engine without additional configuration.
   # Alternatively, you can add a custom entrypoint field in your app.yaml:
   # entrypoint: gunicorn -b :$PORT mysite.wsgi
   app = application

答案 3 :(得分:0)

正如Farzad所说,只需将“ app.py”或“ application.py”或您将应用程序文件保存到“ main.py”的任何名称重命名。如果您无法更改,则使用相同的代码创建另一个项目,但是这次使用应用程序文件名作为“ main.py”