【问题标题】:How to run the getRole command using pymongo?如何使用 pymongo 运行 getRole 命令?
【发布时间】:2018-02-03 20:16:06
【问题描述】:

我想在创建新角色之前检查mongodb 中是否存在角色。我尝试通过以下方式做到这一点:

result = self.client[database].command("getRole", name=app_name)

不幸的是,我收到以下错误:

msg = msg or "%s"
raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: no such command: 'getRole', bad cmd: '{ getRole: 1, name: "test" }'

我指的是这个数据库命令:https://docs.mongodb.com/manual/reference/method/db.getRole/

对于 createRole 我可以执行命令:https://docs.mongodb.com/manual/reference/method/db.createRole/#db.createRole

【问题讨论】:

  • 感谢您的回复。我可以像这样解决问题,但它并不完全相同,因为其他问题要求用户,而我只关心一个特定的角色。
  • 如果您尝试创建存在的角色,则会收到错误消息。为什么不在这里应用请求宽恕而不是许可哲学?

标签: mongodb python-3.x pymongo


【解决方案1】:

Shell methods db.*Database commands 不同。

使用roleInfo command,您可以获得特定角色的信息。

db.command({
    'rolesInfo': {'role': 'noremove','db': 'test'},
    'showPrivileges': True, 'showBuiltinRoles': True
})

上述命令以这种形式返回结果当有匹配的角色时

{'ok': 1.0,
 'roles': [{'db': 'test',
   'inheritedPrivileges': [{'actions': ['find', 'insert', 'update'],
     'resource': {'collection': 'test', 'db': 'test'}}],
   'inheritedRoles': [],
   'isBuiltin': False,
   'privileges': [{'actions': ['find', 'insert', 'update'],
     'resource': {'collection': 'test', 'db': 'test'}}],
   'role': 'noremove',
   'roles': []}]}

当没有匹配的角色时,你会得到这样的结果:

{'ok': 1.0, 'roles': []}

检查某个角色是否存在属于检查返回结果中“角色”列表的长度,如下所示:

noremove_role = db.command({
    'rolesInfo': {'role': 'noremove','db': 'test'},
    'showPrivileges': True, 'showBuiltinRoles': True
})

if not len(noremove_role['roles']):
    # create role
    pass

有没有更好的方法?

是的,根据请求宽恕而不是许可理念,创建角色并处理因尝试添加现有角色而产生的异常。

from pymongo.errors import DuplicateKeyError
import logging

logger = logging.getLogger()

try:
    db.command(
        'createRole', 'noremove',
        privileges=[{
            'actions': ['insert', 'update', 'find'],
            'resource': {'db': 'test', 'collection': 'test'}
        }],
        roles=[])
except DuplicateKeyError:
    logger.error('Role already exists.')
    pass

【讨论】:

  • 感谢您的回复!我没有意识到这一点。关于宽恕方法:我的问题并不完全准确,我也对 getRole 命令的返回值感兴趣,以检查当前权限。但你的回答澄清了这一切。
猜你喜欢
  • 1970-01-01
  • 2015-02-02
  • 2018-03-13
  • 2023-01-25
  • 2014-11-02
  • 1970-01-01
  • 2014-06-01
  • 1970-01-01
  • 2020-07-12
相关资源
最近更新 更多