简体   繁体   中英

Python, Django - Accessing Environment Variables in settings.py

Within my project, I want to send an email with python/Django. In order to do this, I need to specify multiple settings, and one of them is the password for my email. I want to retreive this from an environment variable.

When I reference the environment variable in settings.py, I get a message implying the value is wrong and not my actual password. I ensured that the environment variable is set to my actual password within bash_profile, and when I hardcoded my password in the settings file, the email is sent successfully.

This implies the issue is occurring when trying to retrieve the password as an environment variable.

SETTINGS.py :

import os
# me trying to retrieve password
EMAIL_HOST_PASSWORD = os.environ.get('email_password')

Anybody know the issue? Thank you.

I ensured that the environment variable is set to my actual password within bash_profile

If you are following best practices and running Django in a virtual environment, it has a different set of environment variables. I suspect if you changed your setting to os.environ['email_password'] you would get a KeyError , because that environment variable is not set.

There are a number of ways to export environment variables, but just to prove to yourself that this is the problem, export the value right in the command line with your virtual environment enabled, then run your project and try sending the email.

Edit

Since you're using pipenv, you can simply add a .env file in the root of your project, and pipenv will automatically set those environment variables for you when you activate the virtual environment.

.env

SECRET_KEY=asolidsecretkey
email_password=somesecurepassword
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM