Reputation: 1201
How do safely store passwords and API keys within an .env
file and properly parse them? using python?
I want to store passwords that I do not wish to push into public repos.
Upvotes: 6
Views: 10334
Reputation: 1201
You may parse the key values of an .env
file you can use os.getenv(key)
where you replace key
with the key of the value you want to access
Suppose the contents of the .env
files are :
A=B
FOO=BAR
SECRET=VERYMUCH
You can parse the content like this :
import os
print(os.getenv("A"))
print(os.getenv("FOO"))
print(os.getenv("SECRET"))
# And so on...
Which would result in (output / stdout) :
B
BAR
VERYMUCH
Now, if you are using git version control and you never want yourself to push an environment file accidentally then add this to your .gitignore
file and they'll be conveniently ignored.
.env
(Although you should make your life a bit easier by using an existing .gitignore
template all of which by default ignore .env
files)
Lastly :
.env
just like a text file by doing :with open(".env") as env:
...
and then proceed to manually parse it using regex
.env
files aren't detected by your python script then use this module python-dotenvYou may make use of the aforementioned library like this :
from dotenv import load_dotenv
load_dotenv() # take environment variables from .env.
# Code of your application, which uses environment variables (e.g. from `os.environ` or
# `os.getenv`) as if they came from the actual environment.
Upvotes: 7