繁体   English   中英

使用 Heroku 和 Django 时 Debug=False 时出现 500 错误

[英]500 error when Debug=False with Heroku and Django

当我在部署时在我的 Heroku 应用程序中切换到Debug=False时,我收到一个有趣的 500 错误。 我在部署时设置了 Debug=True 只是为了试用它并且它完美运行 - 所以问题仅在 Debug 设置为 False 时出现。

我不确定从哪里开始。 一些搜索让我相信是白噪声导致了这个问题,但目前还不清楚。 命令:

Output 来自 heroku 日志 --source app

2018-09-13T12:29:53.137785+00:00 app[web.1]: 10.45.76.149 - - [13/Sep/2018:12:29:53 +0000] "GET / HTTP/1.1" 500 27 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0"
2018-09-13T12:29:53.279702+00:00 app[web.1]: 10.81.224.221 - - [13/Sep/2018:12:29:53 +0000] "GET /favicon.ico HTTP/1.1" 404 85 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0"
2018-09-13T12:29:53.792280+00:00 app[web.1]: 10.45.76.149 - - [13/Sep/2018:12:29:53 +0000] "GET /favicon.ico HTTP/1.1" 404 85 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0"

我已尝试按照此解决方案进行修复,但无济于事;

请参阅下面的设置:

import os
import posixpath
from os import environ

# 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.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'A SECRET'

DEBUG = True

ALLOWED_HOSTS = ['*']




SITE_TITLE = "Penguiness"
SITE_TAGLINE = "Amazing records for amazing species"

# Application definition

INSTALLED_APPS = [
    'app',
    # Add your apps here to enable them
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'compressor',
    'gunicorn'
]

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

ROOT_URLCONF = 'Penguinness.urls'


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/


# STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

STATIC_URL = '/static/'

STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['app/static']))

PROJECT_APP_PATH = os.path.dirname(os.path.abspath(__file__))
PROJECT_APP = os.path.basename(PROJECT_APP_PATH)
PROJECT_ROOT = BASE_DIR = os.path.dirname(PROJECT_APP_PATH)


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(PROJECT_ROOT, "app/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',
                'app.context_processors.global_settings',                
            ],
        },
    },
]

WSGI_APPLICATION = 'Penguinness.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

# DATABASES = {
#     'default': {
#         DATABASE STUFF
#     }
# }





SECURE_PROXY_SSL_HEADER = (
    "HTTP_X_FORWARDED_PROTO", 
    "https"
    )





# Password validation
# https://docs.djangoproject.com/en/1.9/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.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_PASSWORD = PASSWORD #my gmail password
EMAIL_HOST_USER = EMAIL  #my gmail username
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER


import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': ('%(asctime)s [%(process)d] [%(levelname)s] ' +
                       'pathname=%(pathname)s lineno=%(lineno)s ' +
                       'funcname=%(funcName)s %(message)s'),
            'datefmt': '%Y-%m-%d %H:%M:%S'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        }
    },
    'handlers': {
        'null': {
            'level': 'DEBUG',
            'class': 'logging.NullHandler',
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose'
        }
    },
    'loggers': {
        'testlogger': {
            'handlers': ['console'],
            'level': 'INFO',
        }
    }
}

好的 - 经过一段时间的战斗,我找到了解决我遇到的两个问题的方法。

问题 1:无法查看 heroku 日志 --source 应用程序:

我必须首先将 LOGGING 添加到 settings.py 文件中:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': ('%(asctime)s [%(process)d] [%(levelname)s] ' +
                       'pathname=%(pathname)s lineno=%(lineno)s ' +
                       'funcname=%(funcName)s %(message)s'),
            'datefmt': '%Y-%m-%d %H:%M:%S'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        }
    },
    'handlers': {
        'null': {
            'level': 'DEBUG',
            'class': 'logging.NullHandler',
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose'
        }
    },
    'loggers': {
        'testlogger': {
            'handlers': ['console'],
            'level': 'INFO',
        }
    }
}

更重要的是让相关错误通过 Heroku 日志向上传播。 为此,在 settings.py 中我写了一行:

DEBUG_PROPAGATE_EXCEPTIONS = True

这给了我一个与我的静态文件相关的错误。 更具体地说,它给了我这个错误:

ValueError: Missing staticfiles manifest entry for 'images/favicon.png'

问题 2:500 错误

在确定处理静态图像有错误后,我搜索并有人建议运行:

python manage.py collectstatic

我这样做了,但仍然发现错误。 接下来是确保 Whitenoise 被注释掉:

#STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

但是,这导致了错误:

2018-09-13T13:13:49.905187+00:00 app[web.1]: "When using Django Compressor together with staticfiles, "
2018-09-13T13:13:49.905190+00:00 app[web.1]: ImproperlyConfigured: When using Django Compressor together with staticfiles, please add 'compressor.finders.CompressorFinder' to the STATICFILES_FINDERS setting.

我尝试添加compressor.finders.CompressorFinder 但这给了我与上面类似的错误。 所以我忽略了这一点。 经过一番搜索后,我发现我必须通过将其添加到 settings.py 来基本上禁用压缩器(至少按照我的理解):

COMPRESS_ENABLED = os.environ.get('COMPRESS_ENABLED', False)

这并没有完全解决问题,因为当时我在定位静态文件时遇到了问题。 所以,我不得不将我的 STATIC_ROOT 设置为:

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

推送到 heroku 就可以了... Debug=False 现在可以工作了

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'

在我的情况下有帮助

对我来说,问题是我评论了 HTML 代码块

<!-- 
Some reference to images.

-->

Collectstatic 忽略注释中引用的图像,但是当 Debug=False 设置时,Django 处理中有一个典型的行为,它实际上尝试解析和验证 HTML 注释中的图像(设置 Debug=True 时不会发生这种情况)。

当我删除评论时,我能够呈现页面并且 500 错误消失了。

原因可能很愚蠢,它可能类似于您在模板中提供的 static 文件路径名。 让我们看一个例子:
代码-1

<img src="{% static '/images/Rectangle 2.png' %}" class="card-img-top" alt="..." >

CODE-2

<img src="{% static 'images/Rectangle 2.png' %}" class="card-img-top" alt="..." >

当 DEBUG=True 时,code1 和 code2 都将正常工作。 但是,如果 DEBUG=False code2 可以正常工作,但 code1 将无法正常工作。 图像前的额外斜杠 (/) 会产生问题,即生产无法正确配置路径。

因此,请查看模板中的 static 文件路径。 这可能是问题所在。

删除后,我在我的应用程序中使用了白噪声:

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

并添加这个:

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'

解决了问题

在django项目的.env文件中设置DEBUG=False在settings中配置DEBUG变量指向.env文件中的变量。 将 DEBUG = False 添加到 Heroku 中的配置中。 我不知道这为什么有效,但我很高兴它确实有效。

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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