【问题标题】:add user to mongodb via python通过python将用户添加到mongodb
【发布时间】:2014-09-01 10:20:28
【问题描述】:

我希望能够将用户添加到 MongoDB,以便我们可以自动安装已包含身份验证的 MongoDB。通过执行此操作,我可以使用 pymongo 成功添加只读用户或 dbOwner 用户:

from pymongo import MongoClient

client = MongoClient('localhost:27017')   
client.admin.authenticate('siteRootAdmin', 'Test123')
client.testdb.add_user('newTestUser', 'Test123', True)

但是当我执行以下代码块来指定角色时,它会失败:

from pymongo import MongoClient

client = MongoClient('localhost:27017')
client.admin.authenticate('siteRootAdmin', 'Test123')
client.testdb.add_user('newTestUser', 'Test123', False, 'readWrite')

出现错误:

line 10, in <module>
    client.admin.add_user('newTestUser', 'Test123', False, 'readWrite')
TypeError: add_user() takes at most 4 arguments (5 given)

在文档中,这意味着您可以为用户文档提供可选字段,例如其他角色。有没有人能够正确设置这些?即,我希望拥有可以将数据添加到集合但没有完整 dbOwner 权限的 readWrite 服务帐户。

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    这里是解决方法:

    client.testdb.add_user('newTestUser', 'Test123', roles=[{'role':'readWrite','db':'testdb'}])
    

    注意:当您要设置“角色”时,应将第三个参数(只读)留空。

    【讨论】:

    • 谢谢!角色的语法是我搞砸的。我曾尝试过 roles = 'readWrite' 但没有注意到 mongodb 既承担了角色又承担了其中的数据库。
    • @rhealitycheck:实际上根据 MongoDB shell 语法,"roles" 应该始终是一个数组,也可以是 roles=["readWrite"] 只要您确保在之后运行此命令选择“testdb”。
    • 如何获得显示成功与否的结果?
    【解决方案2】:

    从版本 3 开始 add_userdeprecated 并且将在以后的版本中被移除。调用时会引起以下警告:

    DeprecationWarning: add_user is deprecated and will be removed in PyMongo 4.0. Use db.command with createUser or updateUser instead
    

    上面的代码可能会被重写为

    client.testdb.command(
        'createUser', 'newTestUser', 
        pwd='Test123',
        roles=[{'role': 'readWrite', 'db': 'testdb'}]
    )
    
    

    【讨论】:

      猜你喜欢
      • 2016-04-22
      • 2021-08-02
      • 2017-08-11
      • 1970-01-01
      • 1970-01-01
      • 2014-06-22
      • 1970-01-01
      • 1970-01-01
      • 2017-10-24
      相关资源
      最近更新 更多