在创建新角色之前,我希望检查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
发布于 2018-02-03 12:09:55
使用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.')
passhttps://stackoverflow.com/questions/48544709
复制相似问题