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.
1st Problem
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
2nd Problem
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')