【问题标题】:How to escape SECRET_KEY in Django from environment file when generated SECRET_KEY begins with '$'?当生成的 SECRET_KEY 以“$”开头时,如何从环境文件中转义 Django 中的 SECRET_KEY?
【发布时间】:2021-01-08 06:21:48
【问题描述】:

在我的 Django 项目中,我有一个 .env 文件,其中包含用于生产设置的 SECRET_KEY

我通过从命令行运行脚本生成了密钥(这里只是打印生成的密钥作为示例)。

python -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())'

恰好生成了一个以'$' 字符开头的密钥。

我的.env 文件看起来像这样。

DJANGO_SECRET_KEY=$*%0e@-7suq*h#2(srya8n&lhb(qy+73xj_db)tpq4qenknk2%

这是通过以下方式在我的生产设置文件中读取的

import os
import environ

env = environ.Env()

# BASE_DIR is the root level directory of the project
env_file = os.path.join(BASE_DIR, '.env')
if os.path.exists(env_file):
    environ.Env.read_env(env_file=env_file) # reading .env file

SECRET_KEY = env('DJANGO_SECRET_KEY')

当我使用此密钥运行我的 Django 项目时,我收到以下错误

django.core.exceptions.ImproperlyConfigured: Set the *%0e@-7suq*h#2(srya8n&lhb(qy+73xj_db)tpq4qenknk2% environment variable

由于'$' 字符,Django 似乎认为密钥值本身就是一个环境变量。这是可以理解的,因为 Bash 中的环境变量具有 '$' 前缀。

但是当我尝试将 .env 文件更改为

DJANGO_SECRET_KEY='$*%0e@-7suq*h#2(srya8n&lhb(qy+73xj_db)tpq4qenknk2%'

DJANGO_SECRET_KEY="$*%0e@-7suq*h#2(srya8n&lhb(qy+73xj_db)tpq4qenknk2%"

我得到同样的错误。

如果生成带有前导 '$' 的密钥(在 DJango 中使用我的生产设置代码),我该如何转义 .env 文件中的 SECRET_KEY?


django 版本:3.0.3

django 环境版本:0.4.5

【问题讨论】:

    标签: python django environment-variables django-settings


    【解决方案1】:

    本文here建议使用pip安装dotenv,彻底简化了隐藏秘钥的过程。至少对于初学者来说。

    【讨论】:

    • 鉴于dotenv 有效,它似乎是 django-environ 包的问题。我将继续使用dotenv。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2020-07-17
    • 2020-11-18
    • 2021-06-10
    • 2017-04-12
    相关资源
    最近更新 更多