简体   繁体   中英

When deploying Django to Heroku: ModuleNotFoundError: No module named 'dotenv'

When deploying Django to Heroku, I get a ModuleNotFoundError: No module named 'dotenv' error. However, I do have python-dotenv listed in my requirements.txt. So I'm very confused about why Heroku is not happy about dotenv.

Here is my requirements.txt:

cffi==1.14.2
cryptography==3.1
dj-database-url==0.5.0
Django==3.1.1
django-cors-headers==3.5.0
django-heroku==0.3.1
django-rest-knox==4.1.0
django-simple-email-confirmation==0.70
djangorestframework==3.11.1
gunicorn==20.0.4
psycopg2==2.8.6
pycparser==2.20
python-dotenv==0.14.0
pytz==2020.1
six==1.15.0
sqlparse==0.3.1
whitenoise==5.2.0

我不知道这是否会有所帮助,但我在部署到 Heroku 时遇到了那个错误,但在我的情况下,我使用的是 pipenv,问题是我所做的要求或任何导入我是在 pip install 而不是 pipenv 中安装它安装,一旦我在那里完成所有安装,它就起作用了,我不记得是否做了类似 pipenv freeze > requirements.txt 的事情

Instead of using python-dotenv try using django-dotenv

Not sure what imports you have in settings.py but try this:

# settings.py
import os
SECRET_KEY = os.getenv('SECRET_KEY')

If you tried to import dotenv at the top of your settings file you may need to remove it.

Also remember to add those environment variables in the 'Config Vars' under the settings of your Heroku app. Those should be there before you push to Heroku.

尝试卸载软件包并再次下载并检查它是否在requirements.txt 文件中。

The purpose of dotenv is to "read key-value pairs from a .env file and set them as environment variables"

Typically the purpose of having a .env file is to have a convenient way of managing your environment locally.

Typically this is not checked into version control (ie it is listed in .gitignore ). The benefits are:

  • Your sensitive environment variables can not be seen by others
  • In production you might want to be able to change these variables without re-deploying
  • Different people can run the app in different environments

Therefore when you deploy to Heroku you typically don't include your .env , and so dotenv has nothing to do.

Instead Heroku has its own way of managing environment variables .

This leaves the problem of what to do in your code where trying to call dotenv on Heroku would give errors like you describe.

One option is to only load it if the environment is not production. Something like this:

import os

if not os.environ.get("PRODUCTION"):
    from dotenv import load_dotenv

    load_dotenv()

Note that you need to set the PRODUCTION environment variable on Heroku, or pick a variable that is already there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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