首页 > 解决方案 > 如何在 Django 的views.py 中使用环境变量?

问题描述

我正在使用python-decouple 3.4为我的 django 应用程序设置环境变量。我的.env文件与manage.py. 除了 SECRET_KEY(在 settings.py 中),在其中一个settings.pyviews.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.pyviews.py直接输入或先输入settings.py再输入,views.py如上例所示]

标签: python-3.xdjangoenvironment-variablespython-decouple

解决方案


我复制了您解释的相同代码,它对我有用。.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)

推荐阅读