你如何从Django的.env文件中加载SECRET_KEY?

huangapple go评论54阅读模式
英文:

How can I load SECRET_KEY from .env file in Django?

问题

这是我的settings.py文件的外观:

import os
import dotenv

dotenv_file = os.path.join(BASE_DIR, ".env")
if os.path.isfile(dotenv_file):
    dotenv.load_dotenv(dotenv_file)

# 更新密钥
SECRET_KEY = os.environ['SECRET_KEY']

这是我的.env文件的外观:

SECRET_KEY="TOPSECRETKEY"

当运行python manage.py migrate时,它会返回KeyError: 'SECRET_KEY'

英文:

This is how my settings.py looks like:

import os
import dotenv

dotenv_file = os.path.join(BASE_DIR, ".env")
if os.path.isfile(dotenv_file):
    dotenv.load_dotenv(dotenv_file)

# UPDATE secret key
SECRET_KEY = os.environ['SECRET_KEY']

This is how my .env file looks like:

SECRET_KEY="TOPSECRETKEY"

When running python manage.py migrate, it returns KeyError: 'SECRET_KEY'

答案1

得分: 1

我找到解决方法了,(供以后参考)
我的 .env 文件与 settings.py 放在同一个文件夹里,但需要放在 manage.py 的同一个文件夹里。

英文:

I figured it out, (for future reference)
My .env file was in the same folder as settings.py and it needed to be in the same folder as manage.py

答案2

得分: 0

你可以使用python-decouple库。

从它的文档中可以看到:

Decouple 帮助你组织你的设置,以便你可以更改参数而不必重新部署你的应用程序。

它还使你可以轻松地:

  1. 将参数存储在ini或.env文件中;
  2. 定义全面的默认值;
  3. 正确转换值为正确的数据类型;
  4. 只有一个配置模块来管理所有的实例。

你可以在库文档中阅读更多信息 <https://pypi.org/project/python-decouple/#usage>

英文:

You can use the python-decouple library.

A resume from its doc:

Decouple helps you to organize your settings so that you can change parameters without having to redeploy your app.

It also makes it easy for you to:

  1. store parameters in ini or .env files;
  2. define comprehensive default values;
  3. properly convert values to the correct data type;
  4. have only one configuration module to rule all your instances.

You can read more in the library documentation itself <https://pypi.org/project/python-decouple/#usage>

huangapple
  • 本文由 发表于 2023年6月22日 04:31:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76526927.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定