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?
You could use os.getenv('SECRET_KEY')
, which will return None
if there is no such environment variable. That's equivalent to os.environ.get('SECRET_KEY')
and similarly allows an optional second argument for a default value (e.g. os.getenv('SECRET_KEY', 'my-default-key')
.
This is the approach that most of the projects I've worked on have taken, both for testing and for local development reasons.
Another approach could be to create a test runner for Django as described at https://pytest-django.readthedocs.io/en/latest/faq.html#how-can-i-use-manage-py-test-with-pytest-django
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