python-3.x - 如何在 Django 的views.py 中使用环境变量?
问题描述
我正在使用python-decouple 3.4为我的 django 应用程序设置环境变量。我的.env
文件与manage.py
. 除了 SECRET_KEY(在 settings.py 中),在其中一个settings.py
或views.py
直接加载其他环境变量失败,说明它们尚未定义。其他给出错误的环境变量将用于views.py
.
这是我的.env
文件:-
SECRET_KEY=<django_app_secret_key>
file_path=<path_to_the file>
如果我尝试将它们定义为settings.py
:-
from decouple import config
FILE_PATH = config('file_path')
然后在 中使用views.py
它们
from django.conf.settings import FILE_PATH
print(FILE_PATH)
然后我也得到同样的错误。如何为我的views.py
具体定义环境变量?
[编辑:这是我得到的错误:-
raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option))
decouple.UndefinedValueError: file_path not found. Declare it as envvar or define a default value.
我是否用过这个
from decouple import config
FILE_PATH = config('file_path')
直接输入settings.py
或views.py
直接输入或先输入settings.py
再输入,views.py
如上例所示]
解决方案
我复制了您解释的相同代码,它对我有用。.env 文件应位于 manage.py 所在的根文件夹中。确保您引用的是相同的设置文件:
python manage.py runserver --settings=yourproj.settings.production
在 .env 文件中:
file_path='/my/path'
在 settings.py 文件中:
from decouple import config
FILE_PATH = config('file_path')
同样在 views.py 文件导入中应该是这样的:
from django.conf import settings
print(settings.FILE_PATH)
推荐阅读
- svelte - 如何将 Svelte 存储与树状嵌套对象一起使用?
- node.js - 将多个值插入 PostreSQL - pg
- python - 从 python 中的 datetime.date 对象获取上一年
- javascript - 一些测试用例没有运行 - 我错过了什么?
- node.js - VSCode 为 WorkSpace 中的每个项目设置不同的主题设置
- javascript - 如何使用 joi 中间件执行 OR 语句并处理错误?
- react-router-dom - react-router-dom:如何在 url 中使用正则表达式捕获组创建路由并在组件中获取它们
- javascript - vue3 chart-js 在悬停时显示以前的数据
- ocr - 如何强制 tika 服务器使用 curl 排除 TesseractOCRParser
- google-cloud-platform - GCP中的服务帐户和服务代理有什么区别