在我的项目中,我想使用python / Django发送电子邮件。为此,我需要指定多个设置,其中之一是我的电子邮件的密码。我想从环境变量中撤出这一点。
当我在settings.py中引用环境变量时,我收到一条消息,提示该值是错误的,而不是我的实际密码。我确保在bash_profile中将环境变量设置为我的实际密码,并且当我在设置文件中对密码进行硬编码时,电子邮件已成功发送。
这意味着在尝试将密码作为环境变量检索时发生了此问题。
SETTINGS.py:
importos# me trying to retrieve passwordEMAIL_HOST_PASSWORD=os.environ.get('email_password')
有人知道这个问题吗?谢谢。
解决方案
我确保将环境变量设置为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...