首页 > 解决方案 > 在 Django Celery 中使用来自 .env 的环境变量

问题描述

我正在使用Django 2.xCelery 4.3.x

在我的Django应用程序中,我使用dotenv.env文件中提供环境变量并加载环境变量,我在manage.pywsgy.py文件中有以下脚本

env_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), '.env')
dotenv.read_dotenv(env_file)

环境变量具有插件使用的 AWS 凭证,以使用SESanymail发送邮件。

现在,我正在使用 Celery 任务发送电子邮件并使用命令行运行 celery worker

celery -A myapp worker -l debug

工作人员正在运行,但是在发送电子邮件时,它在 celery 任务中出现错误,因为

ERROR/ForkPoolWorker-2] An error occurred (AccessDenied) when calling 
the SendRawEmail operation: User `arn:aws:iam::user_id:user/my-laptop` is not 
authorized to permorm this action...

似乎试图与我的笔记本电脑的用户连接,而不是使用.env文件中定义的凭据。

如何使用该.env文件将环境文件提供给 Celery 工作人员?

标签: djangocelerydjango-celerydotenvdjango-anymail

解决方案


通过在celery config文件中加载环境变量解决

celery.py

env_file = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), '.env')
dotenv.read_dotenv(env_file)

推荐阅读