My goal is to email using Python Django without having my email password being shown in the actual code. After some research, I guess I can store my password in an .env file and then access the password from the .env file. So, I currently have an .env file in my Django project with this line of code:
export EMAIL_HOST = 'smtp.gmail.com'
And in my settings.py, I have these:
import environ
env = environ.Env()
environ.Env.read_env()
EMAIL_HOST = os.environ.get('EMAIL_HOST')
print(EMAIL_HOST)
But the printed result is None. print(os.environ) spits out something though. How can I get my .env file to work?
Not only in Django, in general use the library python-dotenv.
from dotenv import load_dotenv
import os
load_dotenv()
EMAIL_HOST = os.getenv("EMAIL_HOST")
https://gist.github.com/josuedjh3/38c521c9091b5c268f2a4d5f3166c497 created a file utils.py in your project.
1: Create an .env file to save your environment variables.
file env.
DJANGO_SECRET_KEY=%jjnu7=54g6s%qjfnhbpw0zeoei=$!her*y(p%!&84rs$4l85io
DJANGO_DATABASE_HOST=database
DJANGO_DATABASE_NAME=master
DJANGO_DATABASE_USER=postgres
2: For security purposes, use permissions 600 sudo chmod 600 .env
3: you can now use the varibles settigns.py
from .utils import load_env
get_env = os.environ.get
BASE_DIR = Path(__file__).parent.parent.parent
SECRET_KEY = get_env("DJANGO_SECRET_KEY", "secret")
This way it can handle multiple environments production or staging
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