I'm working on a Django project in which settings such as SECRET_KEY
are defined in a .env
file, and manage.py
sets the environment variable using python-dotenv as follows:
from dotenv import load_dotenv, find_dotenv
if __name__ == "__main__":
load_dotenv(find_dotenv())
# usual manage.py code
Then settings.py
simply defines module-level settings from environment variables, for example,
SECRET_KEY = os.environ['SECRET_KEY']
I'm now in the process of switching to pytest-django for unit testing. The problem, however, is that without running python manage.py
first, the environment variables don't get set, so I end up with
E KeyError: 'SECRET_KEY'
The way I'm now thinking of working around this is to define a custom action to register with manage.py
to run pytest
(following https://docs.djangoproject.com/en/2.0/howto/custom-management-commands/). This seems a bit like using a sledgehammer to crack a nut, though. Any suggestions of more elegant ways to go about this problem?