本文整理汇总了Python中pymongo.helpers._check_command_response函数的典型用法代码示例。如果您正苦于以下问题:Python _check_command_response函数的具体用法?Python _check_command_response怎么用?Python _check_command_response使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_check_command_response函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: command
def command(sock, dbname, spec, slave_ok, is_mongos, read_preference,
codec_options, check=True, allowable_errors=None):
"""Execute a command over the socket, or raise socket.error.
:Parameters:
- `sock`: a raw socket instance
- `dbname`: name of the database on which to run the command
- `spec`: a command document as a dict, SON, or mapping object
- `slave_ok`: whether to set the SlaveOkay wire protocol bit
- `is_mongos`: are we connected to a mongos?
- `read_preference`: a read preference
- `codec_options`: a CodecOptions instance
- `check`: raise OperationFailure if there are errors
- `allowable_errors`: errors to ignore if `check` is True
"""
ns = dbname + '.$cmd'
flags = 4 if slave_ok else 0
if is_mongos:
spec = message._maybe_add_read_preference(spec, read_preference)
request_id, msg, _ = message.query(flags, ns, 0, -1, spec,
None, codec_options)
sock.sendall(msg)
response = receive_message(sock, 1, request_id)
unpacked = helpers._unpack_response(response, codec_options=codec_options)
response_doc = unpacked['data'][0]
msg = "command %s on namespace %s failed: %%s" % (
repr(spec).replace("%", "%%"), ns)
if check:
helpers._check_command_response(response_doc, msg, allowable_errors)
return response_doc
示例2: __check_response_to_last_error
def __check_response_to_last_error(self, response):
"""Check a response to a lastError message for errors.
`response` is a byte string representing a response to the message.
If it represents an error response we raise OperationFailure.
Return the response as a document.
"""
response = helpers._unpack_response(response)
assert response["number_returned"] == 1
error = response["data"][0]
helpers._check_command_response(error, self.disconnect)
# TODO unify logic with database.error method
if error.get("err", 0) is None:
return error
if error["err"] == "not master":
self.disconnect()
raise AutoReconnect("not master")
if "code" in error:
if error["code"] in [11000, 11001]:
raise DuplicateKeyError(error["err"])
else:
raise OperationFailure(error["err"], error["code"])
else:
raise OperationFailure(error["err"])
示例3: _command
def _command(self, command, value=1,
check=True, allowable_errors=None,
uuid_subtype=OLD_UUID_SUBTYPE, compile_re=True,
read_preference=None, **kwargs):
"""Internal command helper.
"""
if isinstance(command, basestring):
command_name = command.lower()
command = SON([(command, value)])
else:
command_name = command.keys()[0].lower()
as_class = kwargs.pop('as_class', None)
fields = kwargs.pop('fields', None)
if fields is not None and not isinstance(fields, dict):
fields = helpers._fields_list_to_dict(fields)
command.update(kwargs)
orig = mode = read_preference or self.read_preference
if command_name not in SECONDARY_OK_COMMANDS:
mode = ReadPreference.PRIMARY
# Special-case: mapreduce can go to secondaries only if inline
elif command_name == 'mapreduce':
out = command.get('out')
if not isinstance(out, dict) or not out.get('inline'):
mode = ReadPreference.PRIMARY
# Special-case: aggregate with $out cannot go to secondaries.
elif command_name == 'aggregate':
for stage in command.get('pipeline', []):
if '$out' in stage:
mode = ReadPreference.PRIMARY
break
# Warn if mode will override read_preference.
if mode != orig:
warnings.warn("%s does not support %s read preference "
"and will be routed to the primary instead." %
(command_name, orig.name), UserWarning)
cursor = self["$cmd"].find(command,
fields=fields,
limit=-1,
as_class=as_class,
read_preference=mode,
compile_re=compile_re,
_uuid_subtype=uuid_subtype)
for doc in cursor:
result = doc
if check:
msg = "command %s failed: %%s" % repr(command).replace("%", "%%")
helpers._check_command_response(result, self.connection.disconnect,
msg, allowable_errors)
return result, cursor.conn_id
示例4: test_command_response_without_ok
def test_command_response_without_ok(self):
# Sometimes (SERVER-10891) the server's response to a badly-formatted
# command document will have no 'ok' field. We should raise
# OperationFailure instead of KeyError.
self.assertRaises(OperationFailure, helpers._check_command_response, {}, reset=None)
try:
helpers._check_command_response({"$err": "foo"}, reset=None)
except OperationFailure, e:
self.assertEqual(e.args[0], "foo")
示例5: test_mongos_response
def test_mongos_response(self):
error_document = {
'ok': 0,
'errmsg': 'outer',
'raw': {'shard0/host0,host1': {'ok': 0, 'errmsg': 'inner'}}}
try:
helpers._check_command_response(error_document, reset=None)
except OperationFailure, exc:
self.assertEqual('inner', str(exc))
示例6: __simple_command
def __simple_command(self, sock, dbname, spec):
"""Send a command to the server.
"""
rqst_id, msg, _ = message.query(0, dbname + '.$cmd', 0, -1, spec)
sock.sendall(msg)
response = self.__recv_msg(1, rqst_id, sock)
response = helpers._unpack_response(response)['data'][0]
msg = "command %r failed: %%s" % spec
helpers._check_command_response(response, None, msg)
return response
示例7: __simple_command
def __simple_command(self, sock_info, dbname, spec):
"""Send a command to the server.
"""
rqst_id, msg, _ = message.query(0, dbname + ".$cmd", 0, -1, spec)
sock_info.sock.sendall(msg)
response = self.__receive_message_on_socket(1, rqst_id, sock_info)
response = helpers._unpack_response(response)["data"][0]
msg = "command %r failed: %%s" % spec
helpers._check_command_response(response, None, msg)
return response
示例8: test_command_response_without_ok
def test_command_response_without_ok(self):
# Sometimes (SERVER-10891) the server's response to a badly-formatted
# command document will have no 'ok' field. We should raise
# OperationFailure instead of KeyError.
self.assertRaises(OperationFailure,
helpers._check_command_response, {})
try:
helpers._check_command_response({'$err': 'foo'})
except OperationFailure as e:
self.assertEqual(e.args[0], 'foo')
else:
self.fail("_check_command_response didn't raise OperationFailure")
示例9: command
def command(self, command, value=1, check=True, allowable_errors=None, **kwargs):
if isinstance(command, basestring):
command = SON([(command, value)])
command.update(kwargs)
ns = self["$cmd"]
response = yield ns.find_one(command)
if check:
msg = "command {0} on namespace {1} failed: %s".format(repr(command), ns)
_check_command_response(response, msg, allowable_errors)
defer.returnValue(response)
示例10: command
def command(self, command, value=1, check=True, allowable_errors=None, **kwargs):
if isinstance(command, (bytes, unicode)):
command = SON([(command, value)])
options = kwargs.copy()
options.pop("_deadline", None)
command.update(options)
ns = self["$cmd"]
response = yield ns.find_one(command, **kwargs)
if check:
msg = "TxMongo: command {0} on namespace {1} failed with '%s'".format(repr(command), ns)
_check_command_response(response, msg, allowable_errors)
defer.returnValue(response)
示例11: write_command
def write_command(self, request_id, msg):
"""Send "insert" etc. command, returning response as a dict.
Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `request_id`: an int.
- `msg`: bytes, the command message.
"""
self.send_message(msg, 0)
reply = self.receive_message(request_id)
result = reply.command_response()
# Raises NotMasterError or OperationFailure.
helpers._check_command_response(result)
return result
示例12: write_command
def write_command(self, request_id, msg):
"""Send "insert" etc. command, returning response as a dict.
Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `request_id`: an int.
- `msg`: bytes, the command message.
"""
self.send_message(msg, 0)
response = helpers._unpack_response(self.receive_message(1, request_id))
assert response['number_returned'] == 1
result = response['data'][0]
# Raises NotMasterError or OperationFailure.
helpers._check_command_response(result)
return result
示例13: __simple_command
def __simple_command(self, sock_info, dbname, spec):
"""Send a command to the server.
"""
rqst_id, msg, _ = message.query(0, dbname + '.$cmd', 0, -1, spec)
start = time.time()
try:
sock_info.sock.sendall(msg)
response = self.__receive_message_on_socket(1, rqst_id, sock_info)
except:
sock_info.close()
raise
end = time.time()
response = helpers._unpack_response(response)['data'][0]
msg = "command %r failed: %%s" % spec
helpers._check_command_response(response, None, msg)
return response, end - start
示例14: test_mongos_response
def test_mongos_response(self):
error_document = {
'ok': 0,
'errmsg': 'outer',
'raw': {'shard0/host0,host1': {'ok': 0, 'errmsg': 'inner'}}}
with self.assertRaises(OperationFailure) as context:
helpers._check_command_response(error_document)
self.assertEqual('inner', str(context.exception))
# If a shard has no primary and you run a command like dbstats, which
# cannot be run on a secondary, mongos's response includes empty "raw"
# errors. See SERVER-15428.
error_document = {
'ok': 0,
'errmsg': 'outer',
'raw': {'shard0/host0,host1': {}}}
with self.assertRaises(OperationFailure) as context:
helpers._check_command_response(error_document)
self.assertEqual('outer', str(context.exception))
# Raw error has ok: 0 but no errmsg. Not a known case, but test it.
error_document = {
'ok': 0,
'errmsg': 'outer',
'raw': {'shard0/host0,host1': {'ok': 0}}}
with self.assertRaises(OperationFailure) as context:
helpers._check_command_response(error_document)
self.assertEqual('outer', str(context.exception))
示例15: __check_response_to_last_error
def __check_response_to_last_error(self, response):
"""Check a response to a lastError message for errors.
`response` is a byte string representing a response to the message.
If it represents an error response we raise OperationFailure.
Return the response as a document.
"""
response = helpers._unpack_response(response)
assert response["number_returned"] == 1
error = response["data"][0]
helpers._check_command_response(error, self.disconnect)
error_msg = error.get("err", "")
if error_msg is None:
return error
if error_msg.startswith("not master"):
self.disconnect()
raise AutoReconnect(error_msg)
details = error
# mongos returns the error code in an error object
# for some errors.
if "errObjects" in error:
for errobj in error["errObjects"]:
if errobj["err"] == error_msg:
details = errobj
break
if "code" in details:
if details["code"] in (11000, 11001, 12582):
raise DuplicateKeyError(details["err"], details["code"])
else:
raise OperationFailure(details["err"], details["code"])
else:
raise OperationFailure(details["err"])