django 获取环境变量_Python,Django-在settings.py中访问环境变量

在Django项目中发送电子邮件时,作者遇到一个问题,即无法从环境变量正确获取电子邮件密码。当直接在settings.py中硬编码密码时,邮件发送成功。问题在于,在虚拟环境中,环境变量未被正确设置。解决方案包括在激活的虚拟环境中直接通过命令行设置环境变量,或者使用pipenv创建.env文件来自动设置环境变量。
摘要由CSDN通过智能技术生成

在我的项目中,我想使用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...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值