配置不当 DATABASE_NAME env var

Improperly Configured DATABASE_NAME env var

我在与 settings.py 文件相同的目录中创建了一个 .env 文件,其中有一些环境变量,例如:secret_key、database_name 等。但是,它似乎没有在 .env 文件中正确读取数据库名称。我觉得我遵循了文档,但是在推送到 Heroku 时仍然出现配置不正确的错误。不过,当 运行 服务器在本地时它确实有效。

settings.py

from pathlib import Path
import os
from datetime import timedelta

import environ
env = environ.Env()
environ.Env.read_env()

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Take environment variables from .env file
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))

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

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

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env('DEBUG')

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': env('DATABASE_NAME'),
        'USER': env('DATABASE_USER'),
        'PASSWORD': env('DATABASE_PASSWORD'),
        'HOST': env('DATABASE_HOST'),
        'PORT': env('DATABASE_PORT'),
    }
}

.env(示例)

SECRET_KEY=django-insecure-vdihiodnsdkcndocndcndocdcoidcosjvodjv
DEBUG=True

DATABASE_NAME=vjiojjoj3oj3ioj3
DATABASE_USER=vdijvodivjdivfv
...

错误

File "/app/project_name/settings.py", line 94, in <module>
    'NAME': env('DATABASE_NAME'),
  File "/app/.heroku/python/lib/python3.10/site-packages/environ/environ.py", line 175, in __call__
    return self.get_value(
  File "/app/.heroku/python/lib/python3.10/site-packages/environ/environ.py", line 371, in get_value
    raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: Set the DATABASE_NAME environment variable

django-environ 文档:https://github.com/joke2k/django-environ

编辑:好吧,看起来用 .env 文件推送到 Heroku 不是可行的方法。将尝试使用 heroku link 我的 github 回购并在设置中配置变量。我们看看能不能做到。

根据您的编辑判断,您可能已经猜到,Heroku 不支持推送 .env 文件。这是因为它使用了 ephemeral filesystem.

Each dyno gets its own ephemeral filesystem, with a fresh copy of the most recently deployed code. [...] any files written will be discarded the moment the dyno is stopped or restarted. For example, this occurs any time a dyno is replaced due to application deployment and approximately once a day as part of normal dyno management.

你最好使用 Heroku 的内置 config var support。以下是一些示例:

heroku config # View config vars
heroku config:set TEST=test # Sets TEST to "test"
heroku config:unset TEST # Reverses setting TEST
heroku config:get TEST # Returns value of TEST