【问题标题】:Set the DATABASE_URL environment variable设置 DATABASE_URL 环境变量
【发布时间】:2019-01-15 16:08:08
【问题描述】:

我正在尝试通过查看两勺 django 来创建自己的项目结构。项目结构看起来像这样

.环境

.本地

  .django

  .postgres

.生产

 .django

 .postgres

在本地的postgres里面,列出了以下项目

POSTGRES_HOST=postgres
POSTGRES_PORT=5432
POSTGRES_DB=marketing
POSTGRES_USER=username
POSTGRES_PASSWORD=password
DATABASE_URL=postgres://username:password@localhost:5432/marketing

设置文件分为base.py, local.py and production.py 3部分

在base.py中,我配置了DATABASES键如下

DATABASES = {
    'default': env.db('DATABASE_URL'),
}

但是我得到一个错误

django.core.exceptions.ImproperlyConfigured:设置 DATABASE_URL 环境变量

虽然,我在 .envs/.local/.postgres 中有 DATABASE_URL,但我遇到了上述错误。为什么呢?

【问题讨论】:

  • 从您的 shell 中粘贴命令 echo $DATABASE_URL 的输出。

标签: python django django-settings


【解决方案1】:

.myfilename 中的变量之前添加导出。

export POSTGRES_HOST=postgres
export POSTGRES_PORT=5432
export POSTGRES_DB=marketing
export POSTGRES_USER=username
export POSTGRES_PASSWORD=password
export DATABASE_URL=postgres://username:password@localhost:5432/marketing

那就做吧

source .myfilename

【讨论】:

  • 这第一部分不太有用,因为export 将使变量可用于所有子进程,但用户可能不会离开外壳。使用环境变量获取文件,然后从同一个 shell 运行 python 脚本就足够了。 source .myfilename && python myscript.pythis link
  • 可能我错过了 source .postgres 但在 cookiecutter 样板中他们没有使用 export 关键字。
  • 它只能在@tahesse 中运行的当前 shell 中使用
【解决方案2】:

对于基于 python 的解决方案,请检查 this link(归功于用户 @falsetru)。

基本上,添加

import os

with open('.envs/.local/.postgres') as fh:
    os.environ.update(line.strip().split('=', 1) for line in fh)

在您的初始 python 脚本之一中,例如local.py.

【讨论】:

    【解决方案3】:

    我最近遇到了同样的问题。您在文件 .local/.postgres 中的 DATABSE_URL env 变量需要是: DATABASE_URL=postgres://username:password@{DB_SERVICE_NAME}:5432/marketing

    如果您的 docker-compose.yml 的服务名称为 postgres,您可以在此处看到代替 localhost 使用“postgres”。

    【讨论】:

      猜你喜欢
      • 2020-09-06
      • 2021-09-03
      • 1970-01-01
      • 2018-07-13
      • 2014-12-17
      • 2021-04-21
      • 2014-09-24
      • 1970-01-01
      • 2016-02-03
      相关资源
      最近更新 更多