i am using dotenv in a flask project, and have also tested this in a dumbed down test environment as well. I have tried uninstalling and reinstalling etc but the dotenv module cannot be found by python.
When starting flask it sees there are some .env files and tells me to install dotenv even though it is installed and i can see it in flasks system libraries.
When I run code I get a module not found error saying it can't find dotenv. The code is
import os
from dotenv import load_dotenv
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
and the error is
Any advice gratefully accepted.
It's possible that you also have the "dotenv" package installed.
In your virtual environment, try:
pip uninstall dotenv
pip uninstall python-dotenv
pip install python-dotenv
Also you may have dotenv installed at the system level (outside of your virtual environment). If yes, you could try uninstalling that.
If this is not the issue then please post your code and the resultant error.
It turns out there were a number of problems with my code and I will briefly list them here in case anyone else experiences the same problems.
Being reasonably new I am not really clear how the python ecosystem I have installed all hangs together. I have installed Anaconda and Spyder as my development environment. However I have been following a Flask tutorial that uses pip as the installer with virtual environments. The command prompt I use is the one that came with Anaconda. Everything seemed to be working OK somehow, until I got the dotenv problem, which is in fact a tiny detail in the over-all rather large tutorial.
To fix dotenv I was trying all sorts of install/uninstalls with pip, I could see dotenv was installed already! That didn't work. What did work was installing dotenv with conda in my command prompt, but I had to be explicit about where to get dotenv from. The command that worked was
conda install -c conda-forge python-dotenv
Once I got dotenv to install I could not set the environment variables from the .env
file. The tutorial uses os.path.dirname(__file__)
to get the current working directory. It turns out __file__
is always lower case, but my directory has some upper case in it. Consequently the absolute path of the .env
file could not be found! I fixed this by using the built-in pathlib module which respects case. Here is some code.
import os
from pathlib import Path
from dotenv import load_dotenv
# Get the base directory
basepath = Path()
basedir = str(basepath.cwd())
# Load the environment variables
envars = basepath.cwd() / '.env'
load_dotenv(envars)
# Read an environment variable.
SECRET_KEY = os.getenv('SECRET_KEY')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With