Skip to main content
 首页 » 编程设计

python之Django 应用程序部署到 Heroku,应用程序错误,

2024年10月17日34myhome

我正在努力将我的 Django 1.10 应用程序部署到 Heroku。作为序言,我正在使用 Pycharm 并且不得不在某个时候重命名我的项目,但它重构并更改了所有地方的名称所以我希望这与问题无关。当我将此站点推送到 Heroku 时,出现应用程序错误。

错误信息

在 Heroku 应用错误日志中,我看到:

2017-01-13T22:04:48.911324+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=secret-anchorage-68558.herokuapp.com request_id=71351a21-2264-4ca7-ad0a-1ae110d72ca7 fwd="162.247.89.174" dyno= connect= service= status=503 bytes= 
2017-01-13T22:04:49.334411+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=secret-anchorage-68558.herokuapp.com request_id=bf22a256-8780-49ed-8820-c8112833121c fwd="162.247.89.174" dyno= connect= service= status=503 bytes= 

它曾经在我的计算机上本地运行,但现在当我尝试运行该应用程序时,我得到:

python3 manage.py runserver 
 
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f278bc6ea60> 
Traceback (most recent call last): 
File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 226, in wrapper 
fn(*args, **kwargs) 
File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 113, in inner_run 
autoreload.raise_last_exception() 
File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 249, in raise_last_exception 
six.reraise(*_exception) 
File "/usr/local/lib/python3.5/dist-packages/django/utils/six.py", line 685, in reraise 
raise value.with_traceback(tb) 
File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 226, in wrapper 
fn(*args, **kwargs) 
File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 27, in setup 
apps.populate(settings.INSTALLED_APPS) 
File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 85, in populate 
app_config = AppConfig.create(entry) 
File "/usr/local/lib/python3.5/dist-packages/django/apps/config.py", line 116, in create 
mod = import_module(mod_path) 
File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module 
return _bootstrap._gcd_import(name[level:], package, level) 
File "<frozen importlib._bootstrap>", line 986, in _gcd_import 
File "<frozen importlib._bootstrap>", line 969, in _find_and_load 
File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked 
ImportError: No module named 'homelibrary.apps' 

当我尝试推送到 Heroku 时:

git push heroku master 
 
Counting objects: 308, done. 
Delta compression using up to 4 threads. 
Compressing objects: 100% (122/122), done. 
Writing objects: 100% (308/308), 111.03 KiB | 0 bytes/s, done. 
Total 308 (delta 170), reused 308 (delta 170) 
remote: Compressing source files... done. 
remote: Building source: 
remote:  
remote: -----> Python app detected 
remote: -----> Installing python-3.5.2 
remote:      $ pip install -r requirements.txt 
remote:        Collecting dj-database-url==0.4.2 (from -r      /tmp/build_6409be14e6f6fb2a7cd364b66c5920b7/requirements.txt (line 1)) 
remote:          Downloading dj_database_url-0.4.2-py2.py3-none-any.whl 
remote:        Collecting Django==1.10.5 (from -r /tmp/build_6409be14e6f6fb2a7cd364b66c5920b7/requirements.txt (line 2)) 
remote:          Downloading Django-1.10.5-py2.py3-none-any.whl (6.8MB) 
remote:        Collecting gunicorn==19.6.0 (from -r /tmp/build_6409be14e6f6fb2a7cd364b66c5920b7/requirements.txt (line 3)) 
remote:          Downloading gunicorn-19.6.0-py2.py3-none-any.whl (114kB) 
remote:        Collecting psycopg2==2.6.2 (from -r /tmp/build_6409be14e6f6fb2a7cd364b66c5920b7/requirements.txt (line 4)) 
remote:          Downloading psycopg2-2.6.2.tar.gz (376kB) 
remote:        Collecting whitenoise==3.2.3 (from -r /tmp/build_6409be14e6f6fb2a7cd364b66c5920b7/requirements.txt (line 5)) 
remote:          Downloading whitenoise-3.2.3-py2.py3-none-any.whl 
remote:        Installing collected packages: dj-database-url, Django,    gunicorn, psycopg2, whitenoise 
remote:          Running setup.py install for psycopg2: started 
remote:            Running setup.py install for psycopg2: finished with status 'done' 
remote:        Successfully installed Django-1.10.5 dj-database-url-0.4.2 gunicorn-19.6.0 psycopg2-2.6.2 whitenoise-3.2.3 
remote:  
remote:      $ python manage.py collectstatic --noinput 
remote:        Traceback (most recent call last): 
remote:          File "manage.py", line 22, in <module> 
remote:            execute_from_command_line(sys.argv) 
remote:          File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line 
remote:            utility.execute() 
remote:          File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute 
remote:            django.setup() 
remote:          File "/app/.heroku/python/lib/python3.5/site-packages/django/__init__.py", line 27, in setup 
remote:            apps.populate(settings.INSTALLED_APPS) 
remote:          File "/app/.heroku/python/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate 
remote:            app_config = AppConfig.create(entry) 
remote:          File "/app/.heroku/python/lib/python3.5/site-packages/django/apps/config.py", line 116, in create 
remote:            mod = import_module(mod_path) 
remote:          File "/app/.heroku/python/lib/python3.5/importlib/__init__.py", line 126, in   import_module 
remote:            return _bootstrap._gcd_import(name[level:], package, level) 
remote:          File "<frozen importlib._bootstrap>", line 986, in _gcd_import 
remote:          File "<frozen importlib._bootstrap>", line 969, in _find_and_load 
remote:          File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked 
remote:        ImportError: No module named 'homelibrary.apps' 
remote:  
remote:  !     Error while running '$ python manage.py collectstatic --noinput'. 
remote:        See traceback above for details. 
remote:  
remote:        You may need to update application code to resolve this error. 
remote:        Or, you can disable collectstatic for this application: 
remote:  
remote:           $ heroku config:set DISABLE_COLLECTSTATIC=1 
remote:  
remote:        https://devcenter.heroku.com/articles/django-assets 
remote:  !     Push rejected, failed to compile Python app. 
remote:  
remote:  !     Push failed 
remote: Verifying deploy.... 
remote:  
remote: !   Push rejected to secret-anchorage-68558. 
remote:  
To https://git.heroku.com/secret-anchorage-68558.git 
! [remote rejected] master -> master (pre-receive hook declined) 
error: failed to push some refs to 'https://git.heroku.com/secret-anchorage-68558.git' 

我试图通过以下方式禁用 COLLECTSTATIC

heroku config:set DISABLE_COLLECTSTATIC=0 

这看起来充满希望。它允许我将我的代码推送到 Heroku,但是当我尝试

heroku run python3 manage.py migrate 

或

heroku open 

我遇到了与以前相同的错误,但它没有在线显示。

项目结构

---homelibrary 
   ---catalog 
      ---migrations 
      ---static 
         ---css 
         ---images 
            favicon.ico 
      ---templates 
      __init__.py 
      admin.py 
      apps.py 
      forms.py 
      models.py 
      tests.py 
      urls.py 
      views.py 
   ---homelibrary 
      __init__.py 
      settings.py 
      urls.py 
      wsgi.py 
  ---templates (for generic, cross-site forms) 
  ---venv 
  .gitignore.txt 
  db.sqlite3 
  LICENSE 
  manage.py 
  Procfile 
  README.md 
  requirements.txt 
  runtime.txt 

Requirements.txt

dj-database-url==0.4.2 
Django==1.10.5 
gunicorn==19.6.0 
psycopg2==2.6.2 
whitenoise==3.2.3 

配置文件

web: gunicorn homelibrary.wsgi --log-file - 

homelibrary/wsgi.py

import os 
 
from django.core.wsgi import get_wsgi_application 
from whitenoise.django import DjangoWhiteNoise 
 
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "homelibrary.settings") 
 
application = get_wsgi_application() 
application = DjangoWhiteNoise(application) 

homelibrary/settings.py

import os 
import dj_database_url 
 
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 
 
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'My key') 
 
DEBUG = bool(os.environ.get('DJANGO_DEBUG', False)) 
 
ALLOWED_HOSTS = [] 
 
INSTALLED_APPS = [ 
'django.contrib.admin', 
'django.contrib.auth', 
'django.contrib.contenttypes', 
'django.contrib.sessions', 
'django.contrib.messages', 
'django.contrib.staticfiles', 
'homelibrary.apps.CatalogConfig', 
] 
 
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 = 'homelibrary.urls' 
 
TEMPLATES = [ 
{ 
    'BACKEND': 'django.template.backends.django.DjangoTemplates', 
    'DIRS': ['./templates',], 
    '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 = 'homelibrary.wsgi.application' 
 
DATABASES = { 
'default': { 
    'ENGINE': 'django.db.backends.sqlite3', 
    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 
    } 
} 
 
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', 
}, 

]

 LANGUAGE_CODE = 'en-us' 
 
 TIME_ZONE = 'America/New_York' 
 
 USE_I18N = True 
 
 USE_L10N = True 
 
 USE_TZ = True 
 
LOGIN_REDIRECT_URL = '/' 
 
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' 
 
db_from_env = dj_database_url.config(conn_max_age=500) 
DATABASES['default'].update(db_from_env) 
 
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') 
STATIC_URL = '/static/' 

知道我做错了什么吗?

请您参考如下方法:

用这个改变你的INSTALLED_APPS

INSTALLED_APPS = [ 
    'django.contrib.admin', 
    'django.contrib.auth', 
    'django.contrib.contenttypes', 
    'django.contrib.sessions', 
    'django.contrib.messages', 
    'django.contrib.staticfiles', 
    'catalog', 
] 

之后你还会遇到更多的错误

  1. 如果您的 DEBUG 在生产中设置为 False 那么您需要更改 ALLOWED_HOSTS=[] 到 ALLOWED_HOSTS = ['*']

  2. 在settings.py文件中添加

    STATICFILES_STORAGE='whitenoise.django.GzipManifestStaticFilesStorage'

如果它不起作用,那么再做一件事情,看看第 8 步和第 9 步 here.