So I think this is the most common approach...
1. postactivate
with virtualenvwrapper
I've always done this in the postactivate
file myself. In this approach, you can either define environment variables directly in that file (my preference) or in a separate file in your project dir which you source
in the postactivate file. To be specific, this is actually a part of virtualenvwrapper, as opposed to virtualenv itself.
http://virtualenvwrapper.readthedocs.io/en/latest/scripts.html#postactivate
(If you want to be really clean, you can also unset your environment vars in the postdeactivate
file.)
Alternatively, you can do this directly in the activate
file. I find that approach less desirable because there are other things going on in there too.
https://virtualenv.pypa.io/en/latest/userguide.html#activate-script
Two popular alternatives I've also used are:
2. .env
with autoenv
Independent of virtualenv, another approach towards solving the same problem is Kenneth Reitz' autoenv, which automatically sources a .env
whenever you cd into the project directory. I do not use this one much anymore.
https://github.com/kennethreitz/autoenv
3. .env
with Python Decouple
If you only need the environment variables for Python code (and not, for example, in a shell script inside your project) then Python Decouple is a related approach which uses a simplified .env
file in the root of your project. I find myself using it more and more these days personally.
https://github.com/henriquebastos/python-decouple/
I'm somewhat surprised to see this is not discussed in detail in The Hitchhiker's Guide to Python - Virtual Environments. Perhaps we can generate a pull request about it from this question.