如何授予对两个 mongodb 数据库的访问权限,以便在触发 celery 任务后同步写入记录?

How to grant access to two mongodb DB, to write records synchronously, after a celery task is triggered?

我有两个数据库(即test和celery)。当 celery 任务被触发时,它将首先用结果更新 "test" 数据库,然后用 success/failure 消息更新 "celery" 数据库。 我已使用凭据保护这些数据库并遵循此方法: https://medium.com/@matteocontrini/how-to-setup-auth-in-mongodb-3-0-properly-86b60aeef7e8

现在,当我 运行 我的任务时,它给我这个错误:

pymongo.errors.OperationFailure: 无权在 celery 上执行命令 { createIndexes: "celery_taskmeta", indexes: [ { key: { date_done: 1 }, background: "true", 姓名: "date_done_1" } ] }

我正在使用: mongodb:3.4 蒙古引擎:0.16 django 2.1 和 python3

mongoengine.connect(db="test",host=config.host,username="admin_1",
password="admin1234",authentication_source="admin")

CELERY_BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = "mongodb"
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'

除了上面link提到的方法,我试过在admin DB中创建一个admin用户,像这样:

use admin
db.createUser(
 {
   user: "admin_1",
   pwd: "admin1234",
   roles: [ 
{ 
role: "dbOwner",
db: "test" 
},

{ 
role: "userAdminAnyDatabase",
db: "admin" 
},

{ 
role: "dbOwner",
db: "celery" 
}
]
 }
)

同样报错!

错误来自芹菜,它无法在集合上创建索引,因为它未经过身份验证。

您正在正确连接 mongoengine 但在提供的代码片段中,您没有在 celery 配置中提供 username/password 因此它无法进行身份验证(mongoengine 是一个独特的库,它没有共享它的与芹菜隐式连接)。

根据我在 docs 中看到的内容,您可以提供 mongodb URI,如下所示:

CELERY_RESULT_BACKEND = "mongodb://{user}:{password}@127.0.0.1:27017/"

默认情况下,celery 将使用数据库 "celery",因此您不必指定它