简体   繁体   English

Python、Django - 访问 settings.py 中的环境变量

[英]Python, Django - Accessing Environment Variables in settings.py

Within my project, I want to send an email with python/Django.在我的项目中,我想用 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.当我在 settings.py 中引用环境变量时,我收到一条消息,暗示该值错误,而不是我的实际密码。 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.我确保在 bash_profile 中将环境变量设置为我的实际密码,并且当我在设置文件中硬编码我的密码时,电子邮件发送成功。

This implies the issue is occurring when trying to retrieve the password as an environment variable.这意味着在尝试将密码作为环境变量检索时会出现问题。

SETTINGS.py :设置.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我确保在 bash_profile 中将环境变量设置为我的实际密码

If you are following best practices and running Django in a virtual environment, it has a different set of environment variables.如果您遵循最佳实践并在虚拟环境中运行 Django,则它具有一组不同的环境变量。 I suspect if you changed your setting to os.environ['email_password'] you would get a KeyError , because that environment variable is not set.我怀疑如果您将设置更改为os.environ['email_password']您会收到KeyError ,因为该环境变量未设置。

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.由于您使用的是 pipenv,您只需在项目的根目录中添加一个 .env 文件,当您激活虚拟环境时,pipenv 将自动为您设置这些环境变量。

.env .env

SECRET_KEY=asolidsecretkey
email_password=somesecurepassword
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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