简体   繁体   English

如何使用 python-decouple 在预期路径之外加载 .env 文件?

[英]How do you use python-decouple to load a .env file outside the expected paths?

I'm forced to keep my .env file in a non-standard path outside the root of my project (in a separate directory altogether).我被迫将我的.env文件保存在我的项目根目录之外的非标准路径中(完全在一个单独的目录中)。

Let's say I have my Django project in /var/projects/my_project , though I have my .env file in /opt/envs/my-project/.env where my SECRET_KEY is stored.假设我在/var/projects/my_project有我的 Django 项目,尽管我在/opt/envs/my-project/.env中有我的.env文件,我的SECRET_KEY存储在其中。 In my settings.py file, I'd like to explicitly use the .env file at that path so that I can still do this:在我的settings.py文件中,我想在该路径中显式使用.env文件,以便我仍然可以这样做:

from decouple import config
secret_key = config('SECRET_KEY')

I figured it out.我想到了。

Instead of importing decouple.config and doing the usual config('FOOBAR') , create a new decouple.Config object using RepositoryEnv('/path/to/env-file') .不是导入decouple.config并执行通常的config('FOOBAR')config('FOOBAR')使用RepositoryEnv('/path/to/env-file')创建一个新的decouple.Config对象。

from decouple import Config, RepositoryEnv

DOTENV_FILE = '/opt/envs/my-project/.env'
env_config = Config(RepositoryEnv(DOTENV_FILE))

# use the Config().get() method as you normally would since 
# decouple.config uses that internally. 
# i.e. config('SECRET_KEY') = env_config.get('SECRET_KEY')
SECRET_KEY = env_config.get('SECRET_KEY')

Hopefully this helps someone.希望这有助于某人。

If you look at the decouple implementation, config is just a pre-instantiated AutoConfig:如果您查看解耦实现,config 只是一个预先实例化的 AutoConfig:

config = AutoConfig()

But AutoConfig takes as optional argument search_path so we can do the following:但是 AutoConfig 将search_path作为可选参数,因此我们可以执行以下操作:

from decouple import AutoConfig
config = AutoConfig(search_path='/opt/envs/my-project')

Then you can do as usual:然后你可以像往常一样:

secret_key = config('SECRET_KEY')

Now, django-decouple==2.1 supports having settings.ini and .env files in any parent directory of the project dir.现在, django-decouple==2.1支持在项目目录的任何父目录中包含settings.ini.env文件。

(And the old methods don't work anymore. - from decouple import Config, RepositoryEnv does not work, AutoConfig does not have search_path as parameter.) (旧方法不再起作用。-从解耦导入配置,RepositoryEnv 不起作用,AutoConfig 没有 search_path 作为参数。)

This is convenient because you would want to keep the settings.ini in the project folder on your local machine and you would want to have clean checkouts on the staging/prod server, thus the settings.ini is better located outside the project folder.这很方便,因为您希望将settings.ini保留在本地计算机上的项目文件夹中,并且您希望在登台/生产服务器上进行干净的检出,因此settings.ini最好位于项目文件夹之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM