Awesome Python modules - decouple
In these days of open git repositories, be it in github or somewhere else (gitlab,
bitbucket, or even your own little gitea instance) you have
to go the extra mile to keep your secrets secret. The easiest way - and a best practice -
is to just put your configuration in an .env
file that never gets submitted to
the repository in the first place. You do have a .gitignore
file in every repository,
right? RIGHT?
But the problem with these environment files is that they are a bit cumbersome to use.
After all, you do need the variables in your program, not in that file. And you have
to run a source .env
and maybe even export the variables in it because they will
not be visible in subprocesses started by that shell…
In comes python-decouple to save the day. Oh, and btw., thanks to the moron who caught “decouple” on pypi for his one-star project that nobody uses, so Henrique had to call his module “python-decouple”. Well, he got 2267 stars at the time I’m writing this.
Usage
It’s really simple. Just import one thing and use it. Make a .env
file, it’ll get it
from there. Define environment variables, it’ll get it from there. Create a settings.ini
file and it’ll get it from there. If you add defaults you don’t even have to define
anything outside your program. Whatever your preferences are, you can just forget
where it comes from.
Just do this to access the configuration:
from decouple import config
SECRET_KEY = config('SECRET_KEY', default='changeme')
And, as said before, this can come from here:
[settings]
SECRET_KEY=this_is_very_secret
or here:
$ cat .env
SECRET_KEY=this_is_very_secret
or even here:
export SECRET_KEY=super_secret