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

时间:2018-09-13 10:24:42

标签: python django heroku

当我在部署时在Heroku应用程序中切换到Debug=False时,出现了一个有趣的500错误。我在部署时将Debug = True设置为仅用于尝试,它可以完美运行-因此,问题仅在Debug设置为False时出现。

我不确定从哪里开始。一些搜索使我相信这是引起问题的白噪声,但目前尚不清楚。命令:

heroku日志的输出-源应用

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"

我尝试按照此solution进行修复,但无济于事;

有关我的设置,请参见以下内容:

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

5 个答案:

答案 0 :(得分:2)

好的-经过一番奋斗,我找到了解决我遇到的两个问题的方法。

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

我必须首先将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现在可以工作

答案 1 :(得分:1)

Na

对我有帮助

答案 2 :(得分:0)

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

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

并添加:

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

解决了问题

答案 3 :(得分:0)

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

答案 4 :(得分:-1)

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