Heroku/Django 部署:为啥我在成功部署和静态收集时收到错误 500?

Posted

技术标签:

【中文标题】Heroku/Django 部署:为啥我在成功部署和静态收集时收到错误 500?【英文标题】:Heroku/Django deploy: why am I getting an error 500 with successful deploy and static collection?Heroku/Django 部署:为什么我在成功部署和静态收集时收到错误 500? 【发布时间】:2019-05-10 16:25:47 【问题描述】:

几个月来,我一直在努力在 Heroku 上部署我的第一个 Django 站点。我使用git push heroku master 成功构建并使用heroku run python manage.py collectstatic --noinput 成功收集静态文件,但是当DEBUG = config('DEBUG', default=False, cast=bool) 时,我无法让站点在没有错误500 的情况下提供服务。当 DEBUG 设置为 True 时,该站点确实可以工作(尽管我将不得不弄清楚如何使数据库正常工作)。我认为我允许的主机设置正确。我可以在 SO 上找到的所有答案都不能完全解决我的问题。

我添加了来自 this answer 的日志记录,这在日志中提供了更多信息,但我不明白为什么当我能够成功收集静态文件时它们不可用?

2018-12-09T16:24:38.181428+00:00 heroku[web.1]: State changed from starting to up
2018-12-09T16:24:39.173376+00:00 app[web.1]: /app/.heroku/python/lib/python2.7/site-packages/whitenoise/base.py:104: UserWarning: No directory at: /app/staticfiles/
2018-12-09T16:24:39.173419+00:00 app[web.1]: warnings.warn(u'No directory at: '.format(root))
2018-12-09T16:24:39.173421+00:00 app[web.1]: /app/.heroku/python/lib/python2.7/site-packages/whitenoise/base.py:104: UserWarning: No directory at: /app/staticfiles/
2018-12-09T16:24:39.173423+00:00 app[web.1]: warnings.warn(u'No directory at: '.format(root))

我显然错过了很多,任何指导将不胜感激。

编辑添加:

settings.py

import os
import dj_database_url
from decouple import config

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', default=False, cast=bool)

ALLOWED_HOSTS = [
    'localhost',
    '127.0.0.1',
    'tallymusic.herokuapp.com',
    '.tallymusic.net'
]

# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # user-created apps
    'concerts',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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 = 'tallymusic.urls'

TEMPLATES = [
    
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, '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 = 'tallymusic.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = 
    'default': dj_database_url.config(
        default=config('DATABASE_URL')
    )

""" # dev
DATABASES = 
    'default': 
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    

"""

# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

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',
    ,
]

# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'EST'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# Static files (CSS, javascript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/assets/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'assets'),
    os.path.join(BASE_DIR, 'assets/css'),
    os.path.join(BASE_DIR, 'assets/images'),
    os.path.join(BASE_DIR, 'assets/js'),
)

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

# https://***.com/questions/15128135/setting-debug-false-causes-500-error
LOGGING = 
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': 
        'verbose': 
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        ,
        'simple': 
            'format': '%(levelname)s %(message)s'
        ,
    ,
    'handlers': 
        'file': 
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'mysite.log',
            'formatter': 'verbose'
        ,
    ,
    'loggers': 
        'django': 
            'handlers':['file'],
            'propagate': True,
            'level':'DEBUG',
        ,
        'MYAPP': 
            'handlers': ['file'],
            'level': 'DEBUG',
        ,
    

更多日志

2018-12-09T16:24:14.000000+00:00 app[api]: Build started by user ME
2018-12-09T16:24:29.581094+00:00 heroku[web.1]: Restarting
2018-12-09T16:24:29.581759+00:00 heroku[web.1]: State changed from up to starting
2018-12-09T16:24:30.254016+00:00 app[web.1]: [2018-12-09 16:24:30 +0000] [4] [INFO] Handling signal: term
2018-12-09T16:24:30.254190+00:00 app[web.1]: [2018-12-09 11:24:30 +0000] [11] [INFO] Worker exiting (pid: 11)
2018-12-09T16:24:30.255609+00:00 app[web.1]: [2018-12-09 11:24:30 +0000] [12] [INFO] Worker exiting (pid: 12)
2018-12-09T16:24:30.297433+00:00 app[web.1]: [2018-12-09 16:24:30 +0000] [4] [INFO] Shutting down: Master
2018-12-09T16:24:30.245505+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2018-12-09T16:24:30.366997+00:00 heroku[web.1]: Process exited with status 0
2018-12-09T16:24:29.201161+00:00 app[api]: Deploy eff240d7 by user ME
2018-12-09T16:24:29.201161+00:00 app[api]: Release v23 created by user ME
2018-12-09T16:24:34.427399+00:00 heroku[web.1]: Starting process with command `gunicorn tallymusic.wsgi --log-file -`
2018-12-09T16:24:36.000000+00:00 app[api]: Build succeeded
2018-12-09T16:24:37.293769+00:00 app[web.1]: [2018-12-09 16:24:37 +0000] [4] [INFO] Starting gunicorn 19.9.0
2018-12-09T16:24:37.294491+00:00 app[web.1]: [2018-12-09 16:24:37 +0000] [4] [INFO] Listening at: http://0.0.0.0:3342 (4)
2018-12-09T16:24:37.296193+00:00 app[web.1]: [2018-12-09 16:24:37 +0000] [4] [INFO] Using worker: sync
2018-12-09T16:24:37.315139+00:00 app[web.1]: [2018-12-09 16:24:37 +0000] [11] [INFO] Booting worker with pid: 11
2018-12-09T16:24:37.380085+00:00 app[web.1]: [2018-12-09 16:24:37 +0000] [12] [INFO] Booting worker with pid: 12
2018-12-09T16:24:38.181428+00:00 heroku[web.1]: State changed from starting to up
2018-12-09T16:24:39.173376+00:00 app[web.1]: /app/.heroku/python/lib/python2.7/site-packages/whitenoise/base.py:104: UserWarning: No directory at: /app/staticfiles/
2018-12-09T16:24:39.173419+00:00 app[web.1]: warnings.warn(u'No directory at: '.format(root))
2018-12-09T16:24:39.173421+00:00 app[web.1]: /app/.heroku/python/lib/python2.7/site-packages/whitenoise/base.py:104: UserWarning: No directory at: /app/staticfiles/
2018-12-09T16:24:39.173423+00:00 app[web.1]: warnings.warn(u'No directory at: '.format(root))

【问题讨论】:

从发布的答案中,您是否设置了正确的 ALLOWED_HOSTS,您能否添加更多日志和 manage.py 文件 我认为允许的主机设置正确,根据要求添加了我的 settings.py 和更多日志。 您需要检查 collect static 将文件放在哪里似乎文件夹 staticfiles 没有在您的 STATIC_ROOT 的正确位置创建 按照这些步骤devcenter.heroku.com/articles/django-assets 【参考方案1】:

您很可能已经解决了这个问题,但这是为将来遇到问题的其他人准备的。

大多数网站和人们说您需要像这样更新settings.py 中的ALLOWED_HOSTS['www.beta800.net', '127.0.0.1'](或['*'] 用于快速测试,而不是用于生产)。

对我来说,这并没有解决问题,尽管更新ALLOWED_HOSTS 很重要。我的问题是我的应用程序缺少静态文件文件夹。如果日志向您显示类似以下的错误:UserWarning: No directory at:/app/static/ warnings.warn(u'No directory at: '.format(root)) 这也是您的应用程序中的问题。如果是这种情况,请按照以下步骤操作:

    在本地,将settings.py 中的DEBUG 属性更改为True

    确保您在settings.py 中设置了以下属性:

# The URL to use when referring to static files (where they will be served from)
STATIC_URL = '/static/'

# The absolute path to the directory where collectstatic will collect static files for deployment.
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

    在本地,将名为static 的文件夹添加到根文件夹。

    在本地,运行 python manage.py collectstatic。这应该会在您的应用程序的根文件夹中创建另一个名为 staticfiles 的文件夹。

    现在您可以将settings.py 中的DEBUG 属性设置为False 并部署您的应用。

【讨论】:

以上是关于Heroku/Django 部署:为啥我在成功部署和静态收集时收到错误 500?的主要内容,如果未能解决你的问题,请参考以下文章

Heroku:Django Migration 版本未在部署中运行

部署Django+React到Heroku - 未捕获的语法错误。意外的标记'<'

Pandas数据框一旦部署到heroku(Django项目)后就无法按预期方式运行

Heroku django 项目只读文件系统

Heroku Django 应用程序错误:工作人员超时问题 (H12)

将网络测功机添加到 Heroku django 应用程序时如何克服“无法找到该编队”错误?