Need an example and please explain me the purpose of python-dotenv.
I am kind of confused with the documentation.
3 Answers
From the Github page:
Reads the key,value pair from .env and adds them to environment variable. It is great of managing app settings during development and in production using 12-factor principles.
Assuming you have created the .env file along-side your settings module.
. ├── .env └── settings.py Add the following code to your settings.py:
# settings.py import os from os.path import join, dirname from dotenv import load_dotenv dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_path) SECRET_KEY = os.environ.get("SECRET_KEY") DATABASE_PASSWORD = os.environ.get("DATABASE_PASSWORD") .env is a simple text file with each environment variable listed one per line, in the format of KEY="Value". The lines starting with # are ignored.
SOME_VAR=someval # I am a comment and that is OK FOO="BAR" 11In addition to @Will's answer, the python-dotenv module comes with a find_dotenv() that will try to find the .env file.
# settings.py import os from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv()) SECRET_KEY = os.environ.get("SECRET_KEY") DATABASE_PASSWORD = os.environ.get("DATABASE_PASSWORD") 1You could set the env variables like this:
export PRIVATE_KEY=0X32323 and then read it with os module.
import os private_key=os.getenv("PRIVATE_KEY") But this way, environment variable works only for the duration that shell is live. If you close the shell and restart it, you have to set environmental variable again. python-dotenv prevents us from doing this repetitive work.For this create .env file and add variables in this format
PRIVATE_KEY=fb6b05d6e75a93e30e22334443379292ccd29f5d815ad93a86ee23e749227 then in the file u want to access anv variables
import os from dotenv import load_dotenv #default directory for .env file is the current directory #if you set .env in different directory, put the directory address load_dotenv("directory_of_.env) load_dotenv() load_dotenv() will set the environment variables from .env and we access with os module
private_key=os.getenv("PRIVATE_KEY")