简体   繁体   English

python-dotenv 在自定义包中不起作用

[英]python-dotenv not working in custom package

I have been using python-dotenv successfully in my python app.我一直在我的 python 应用程序中成功使用 python-dotenv。 I am now starting to refactor and creating packages to hold some of my support files.我现在开始重构和创建包来保存我的一些支持文件。 When i move the .env file into the package folder my env variables are not set.当我将 .env 文件移动到包文件夹中时,我的 env 变量没有设置。

As an example举个例子

The following structure works.以下结构有效。

/
- app.py
- .env
#app.py
import os
from dotenv import load_dotenv
load_dotenv()
print(os.getenv("DB_PASSWORD"))

Result: kdfhsffdfjd结果: kdfhsffdfjd

The following structure does not work以下结构不起作用

/
- database
  - __init__.py
  - connection.py
  - .env
- app.py
#connection.py
import os
from dotenv import load_dotenv
load_dotenv()
print(os.getenv("DB_PASSWORD"))

Result: None结果:

# app.py
from database import connection

You need to actually call load_dotenv function.您需要实际调用load_dotenv函数。 You can pass the .env file path as an argument or you could try to use find_dotenv method:您可以将 .env 文件路径作为参数传递,或者您可以尝试使用find_dotenv方法:

from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())

# or
load_dotenv(path_to_dotenv_file)

The solution was to keep the .env file in the root of my project.解决方案是将 .env 文件保留在我项目的根目录中。 This makes sense on a number of levels.这在许多层面上都是有意义的。

  1. It ensures that only one .env file exists.它确保只存在一个 .env 文件。
  2. The whole point of the .env file is that I don't want to publish my secrets in the Git repo. .env 文件的全部意义在于我不想在 Git 存储库中发布我的秘密。 If the .env file was located in the package, users would have to edit the package by adding a .env file, potentially in multiple places.如果 .env 文件位于包中,则用户必须通过添加 .env 文件来编辑包,可能在多个位置。

Anyway, in summary, I can still use load_dotenv() in the package, but the .env file had to be in the root of the project.无论如何,总而言之,我仍然可以在包中使用 load_dotenv(),但是 .env 文件必须在项目的根目录中。 @GProst has suggested that I should be able to access it in the package, but I was not able to get that to work. @GProst 建议我应该能够在包中访问它,但我无法让它工作。

for future reference, I had the same problem, but none of the above helped - I was using pipenv, and it turns out I that when I was running the pipenv shell from another location, which isn't the project root folder, it wouldn't load antything from the .env file.为了将来参考,我遇到了同样的问题,但以上都没有帮助 - 我使用的是 pipenv,结果是当我从另一个位置(不是项目根文件夹)运行 pipenv shell 时,它不会不从 .env 文件加载 antything。 after deactivating the shell, and running it again from the root folder, it worked fine.停用外壳并从根文件夹再次运行它后,它工作正常。

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

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