本文整理汇总了Python中twisted.python.failure.Failure方法的典型用法代码示例。如果您正苦于以下问题:Python failure.Failure方法的具体用法?Python failure.Failure怎么用?Python failure.Failure使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.python.failure
的用法示例。
在下文中一共展示了failure.Failure方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testIllegalInboxDelete
# 需要导入模块: from twisted.python import failure [as 别名]
# 或者: from twisted.python.failure import Failure [as 别名]
def testIllegalInboxDelete(self):
"""
Test what happens if we try to delete the user Inbox.
We expect that operation to fail.
"""
self.stashed = None
def login():
return self.client.login(TEST_USER, TEST_PASSWD)
def delete():
return self.client.delete('inbox')
def stash(result):
self.stashed = result
d1 = self.connected.addCallback(strip(login))
d1.addCallbacks(strip(delete), self._ebGeneral)
d1.addBoth(stash)
d1.addCallbacks(self._cbStopClient, self._ebGeneral)
d2 = self.loopback()
d = defer.gatherResults([d1, d2])
d.addCallback(lambda _: self.failUnless(isinstance(self.stashed,
failure.Failure)))
return d
示例2: send
# 需要导入模块: from twisted.python import failure [as 别名]
# 或者: from twisted.python.failure import Failure [as 别名]
def send(self, cmd, args, expect_ack=None, ack_callback=None, response_callback=None, expect_status=None, status_callback=None, update_callback=None, update_handler=None):
if self.ready:
self.cmd = cmd
if 'request' in cmd:
self.response_rows = []
ret = self.api.gateway_send('%s %s %s' % (cmd, self.id, args))
self.ack_pending = expect_ack
self.ack_callback = ack_callback
self.response_pending = bool(response_callback)
self.response_callback = response_callback
self.status_pending = expect_status
self.status_callback = status_callback
self.update_callback = update_callback
self.update_handler = update_handler
else:
if self.on_connect_action:
self.api.error_handler(self.id, 'Failure: on_connect_action already exists: %s' % repr(self.on_connect_action))
ret = False
else:
self.api.output('%s storing on_connect_action (%s)...' % (self, cmd))
self.on_connect_action = (cmd, args, expect_ack, ack_callback, response_callback, expect_status, status_callback, update_callback, update_handler)
ret = True
return ret
示例3: set_order_route
# 需要导入模块: from twisted.python import failure [as 别名]
# 或者: from twisted.python.failure import Failure [as 别名]
def set_order_route(self, route, callback):
#print('set_order_route(%s, %s) type=%s %s' % (repr(route), repr(callback), type(route), (type(route) in [str, unicode])))
if type(route) in [str, unicode]:
if route.startswith('{'):
route = json.loads(route)
elif route.startswith('"'):
route = {json.loads(route): None}
else:
route = {route: None}
if (type(route)==dict) and (len(route.keys()) == 1) and (type(route.keys()[0]) in [str, unicode]):
self.order_route = route
if callback:
self.get_order_route(callback)
else:
if callback:
callback.errback(Failure(Exception('cannot set order route %s' % route)))
else:
self.error_handler(None, 'Cannot set order route %s' % repr(route))
示例4: _complete_batch_send
# 需要导入模块: from twisted.python import failure [as 别名]
# 或者: from twisted.python.failure import Failure [as 别名]
def _complete_batch_send(self, resp):
"""Complete the processing of our batch send operation
Clear the deferred tracking our current batch processing
and reset our retry count and retry interval
Return none to eat any errors coming from up the deferred chain
"""
self._batch_send_d = None
self._req_attempts = 0
self._retry_interval = self._init_retry_interval
if isinstance(resp, Failure) and not resp.check(tid_CancelledError,
CancelledError):
log.error(
"Failure detected in _complete_batch_send: %r", resp,
exc_info=(resp.type, resp.value, resp.getTracebackObject()),
)
return
示例5: test_consumer_error_during_offset
# 需要导入模块: from twisted.python import failure [as 别名]
# 或者: from twisted.python.failure import Failure [as 别名]
def test_consumer_error_during_offset(self):
topic = 'error_during_offset'
part = 991
reqs_ds = [Deferred(), Deferred()]
clock = MemoryReactorClock()
mockclient = Mock(reactor=clock)
mockclient.send_offset_request.side_effect = reqs_ds
consumer = Consumer(mockclient, topic, part, Mock())
d = consumer.start(OFFSET_LATEST)
# Make sure request for offset was made
request = OffsetRequest(topic, part, OFFSET_LATEST, 1)
mockclient.send_offset_request.assert_called_once_with([request])
# Errback the first request
f = Failure(KafkaUnavailableError()) # Perhaps kafka wasn't up yet...
with patch.object(kconsumer, 'log'):
reqs_ds[0].errback(f)
# Advance the clock to trigger the 2nd request
clock.advance(consumer.retry_delay + 1) # fire the callLater
self.assertEqual(2, mockclient.send_offset_request.call_count)
# Stop the consumer to cleanup any outstanding operations
self.assertIsNone(consumer.stop())
self.assertIsNone(self.successResultOf(d))
示例6: test_consumer_offset_out_of_range_error_without_reset
# 需要导入模块: from twisted.python import failure [as 别名]
# 或者: from twisted.python.failure import Failure [as 别名]
def test_consumer_offset_out_of_range_error_without_reset(self):
topic = 'offset_out_of_range_error'
part = 911
offset = 10000
fetch_ds = [Deferred()]
clock = MemoryReactorClock()
mockclient = Mock(reactor=clock)
mockclient.send_fetch_request.side_effect = fetch_ds
consumer = Consumer(mockclient, topic, part, Mock())
d = consumer.start(offset)
f = Failure(OffsetOutOfRangeError())
fetch_ds[0].errback(f)
self.assertEqual(self.failureResultOf(d), f)
consumer.stop()
示例7: test_consumer_error
# 需要导入模块: from twisted.python import failure [as 别名]
# 或者: from twisted.python.failure import Failure [as 别名]
def test_consumer_error(self):
"""
get an unexpected stop error from a consumer
"""
client = self.mock_client([])
processor = Mock()
group = ConsumerGroup(client, "group_id", "topic1", processor)
start_d = group.start()
self.assertNoResult(start_d)
with patch('afkak._group.Consumer') as mock_consumer:
mock_consumer.return_value.start.return_value = d = defer.Deferred()
group.on_join_complete({"topic1": [1]})
self.assertEqual(mock_consumer.return_value.start.called, True)
d.errback(Failure(AssertionError()))
self.failureResultOf(start_d, AssertionError)
d.addErrback(lambda result: None)
示例8: test_producer_send_messages_no_retry_fail
# 需要导入模块: from twisted.python import failure [as 别名]
# 或者: from twisted.python.failure import Failure [as 别名]
def test_producer_send_messages_no_retry_fail(self):
client = Mock(reactor=MemoryReactorClock())
f = Failure(BrokerNotAvailableError())
client.send_produce_request.side_effect = [fail(f)]
client.topic_partitions = {self.topic: [0, 1, 2, 3]}
client.metadata_error_for_topic.return_value = False
msgs = [self.msg("one"), self.msg("two")]
producer = Producer(client, max_req_attempts=1)
d = producer.send_messages(self.topic, msgs=msgs)
# Check the expected request was sent
msgSet = create_message_set(
make_send_requests(msgs), producer.codec)
req = ProduceRequest(self.topic, 0, msgSet)
client.send_produce_request.assert_called_once_with(
[req], acks=producer.req_acks, timeout=producer.ack_timeout,
fail_on_error=False)
self.failureResultOf(d, BrokerNotAvailableError)
producer.stop()
示例9: test_producer_send_messages_unexpected_err
# 需要导入模块: from twisted.python import failure [as 别名]
# 或者: from twisted.python.failure import Failure [as 别名]
def test_producer_send_messages_unexpected_err(self):
client = Mock(reactor=MemoryReactorClock())
f = Failure(TypeError())
client.send_produce_request.side_effect = [fail(f)]
client.topic_partitions = {self.topic: [0, 1, 2, 3]}
client.metadata_error_for_topic.return_value = False
msgs = [self.msg("one"), self.msg("two")]
producer = Producer(client)
# FIXME: Don't use patch to test logging
with patch.object(aProducer, 'log') as klog:
d = producer.send_messages(self.topic, msgs=msgs)
klog.error.assert_called_once_with(
'Unexpected failure: %r in _handle_send_response', f)
self.failureResultOf(d, TypeError)
producer.stop()
示例10: test_producer_stop_during_request
# 需要导入模块: from twisted.python import failure [as 别名]
# 或者: from twisted.python.failure import Failure [as 别名]
def test_producer_stop_during_request(self):
"""
Test stopping producer while it's waiting for reply from client
"""
clock = MemoryReactorClock()
client = Mock(reactor=clock)
f = Failure(BrokerNotAvailableError())
ret = [fail(f), Deferred()]
client.send_produce_request.side_effect = ret
client.topic_partitions = {self.topic: [0, 1, 2, 3]}
client.metadata_error_for_topic.return_value = False
msgs = [self.msg("one"), self.msg("two")]
batch_n = 2
producer = Producer(client, batch_every_n=batch_n, batch_send=True)
d = producer.send_messages(self.topic, msgs=msgs)
# At first, there's no result. Have to retry due to first failure
self.assertNoResult(d)
clock.advance(producer._retry_interval)
producer.stop()
self.failureResultOf(d, tid_CancelledError)
示例11: test_producer_stop_waiting_to_retry
# 需要导入模块: from twisted.python import failure [as 别名]
# 或者: from twisted.python.failure import Failure [as 别名]
def test_producer_stop_waiting_to_retry(self):
"""
Test stopping producer while it's waiting to retry a request
"""
clock = MemoryReactorClock()
client = Mock(reactor=clock)
f = Failure(BrokerNotAvailableError())
ret = [fail(f)]
client.send_produce_request.side_effect = ret
client.topic_partitions = {self.topic: [0, 1, 2, 3]}
client.metadata_error_for_topic.return_value = False
msgs = [self.msg("one"), self.msg("two")]
batch_n = 2
producer = Producer(client, batch_every_n=batch_n, batch_send=True)
d = producer.send_messages(self.topic, msgs=msgs)
# At first, there's no result. Have to retry due to first failure
self.assertNoResult(d)
# Advance the clock, some, but not enough to retry
clock.advance(producer._retry_interval / 2)
# Stop the producer before the retry
producer.stop()
self.failureResultOf(d, tid_CancelledError)
示例12: process
# 需要导入模块: from twisted.python import failure [as 别名]
# 或者: from twisted.python.failure import Failure [as 别名]
def process(self):
"""
Process a request.
"""
# get site from channel
self.site = self.channel.site
# set various default headers
self.setHeader(b'server', version)
self.setHeader(b'date', http.datetimeToString())
# Resource Identification
self.prepath = []
self.postpath = list(map(unquote, self.path[1:].split(b'/')))
try:
resrc = self.site.getResourceFor(self)
if resource._IEncodingResource.providedBy(resrc):
encoder = resrc.getEncoder(self)
if encoder is not None:
self._encoder = encoder
self.render(resrc)
except:
self.processingFailed(failure.Failure())
示例13: handleResponse
# 需要导入模块: from twisted.python import failure [as 别名]
# 或者: from twisted.python.failure import Failure [as 别名]
def handleResponse(self, response):
if self.quietLoss:
return
if self.failed:
self.factory.noPage(
Failure(
error.Error(
self.status, self.message, response)))
if self.factory.method == b'HEAD':
# Callback with empty string, since there is never a response
# body for HEAD requests.
self.factory.page(b'')
elif self.length != None and self.length != 0:
self.factory.noPage(Failure(
PartialDownloadError(self.status, self.message, response)))
else:
self.factory.page(response)
# server might be stupid and not close connection. admittedly
# the fact we do only one request per connection is also
# stupid...
self.transport.loseConnection()
示例14: request
# 需要导入模块: from twisted.python import failure [as 别名]
# 或者: from twisted.python.failure import Failure [as 别名]
def request(self, method, uri, headers=None, bodyProducer=None):
"""
Issue a request to the server indicated by the given C{uri}.
An existing connection from the connection pool may be used or a new
one may be created.
I{HTTP} and I{HTTPS} schemes are supported in C{uri}.
@see: L{twisted.web.iweb.IAgent.request}
"""
parsedURI = URI.fromBytes(uri)
try:
endpoint = self._getEndpoint(parsedURI)
except SchemeNotSupported:
return defer.fail(Failure())
key = (parsedURI.scheme, parsedURI.host, parsedURI.port)
return self._requestWithEndpoint(key, endpoint, method, parsedURI,
headers, bodyProducer,
parsedURI.originForm)
示例15: _handleRedirect
# 需要导入模块: from twisted.python import failure [as 别名]
# 或者: from twisted.python.failure import Failure [as 别名]
def _handleRedirect(self, response, method, uri, headers, redirectCount):
"""
Handle a redirect response, checking the number of redirects already
followed, and extracting the location header fields.
"""
if redirectCount >= self._redirectLimit:
err = error.InfiniteRedirection(
response.code,
b'Infinite redirection detected',
location=uri)
raise ResponseFailed([Failure(err)], response)
locationHeaders = response.headers.getRawHeaders(b'location', [])
if not locationHeaders:
err = error.RedirectWithNoLocation(
response.code, b'No location header field', uri)
raise ResponseFailed([Failure(err)], response)
location = self._resolveLocation(uri, locationHeaders[0])
deferred = self._agent.request(method, location, headers)
def _chainResponse(newResponse):
newResponse.setPreviousResponse(response)
return newResponse
deferred.addCallback(_chainResponse)
return deferred.addCallback(
self._handleResponse, method, uri, headers, redirectCount + 1)