本文整理汇总了Python中twisted.internet.defer.Deferred.cancel方法的典型用法代码示例。如果您正苦于以下问题:Python Deferred.cancel方法的具体用法?Python Deferred.cancel怎么用?Python Deferred.cancel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet.defer.Deferred
的用法示例。
在下文中一共展示了Deferred.cancel方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: BOBI2PClientFactory
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import cancel [as 别名]
class BOBI2PClientFactory(ClientFactory):
protocol = I2PClientTunnelCreatorBOBClient
bobProto = None
canceled = False
removeTunnelWhenFinished = True
def _cancel(self, d):
self.bobProto.sender.transport.abortConnection()
self.canceled = True
def __init__(self, reactor, clientFactory, bobEndpoint, dest,
tunnelNick=None,
inhost='localhost',
inport=None,
options=None):
self._reactor = reactor
self._clientFactory = clientFactory
self._bobEndpoint = bobEndpoint
self.dest = dest
self.tunnelNick = tunnelNick
self.inhost = inhost
self.inport = inport
self.options = options
self.deferred = Deferred(self._cancel);
def buildProtocol(self, addr):
proto = self.protocol()
proto.factory = self
self.bobProto = proto
return proto
def bobConnectionFailed(self, reason):
if not self.canceled:
self.deferred.errback(reason)
# This method is not called if an endpoint deferred errbacks
def clientConnectionFailed(self, connector, reason):
self.bobConnectionFailed(reason)
def i2pTunnelCreated(self):
# BOB is now listening for a tunnel.
# BOB only listens on TCP4 (for now).
clientEndpoint = TCP4ClientEndpoint(self._reactor, self.inhost, self.inport)
# Wrap the client Factory.
wrappedFactory = BOBClientFactoryWrapper(self._clientFactory,
self._bobEndpoint,
I2PAddress(self.localDest),
self.tunnelNick,
self.removeTunnelWhenFinished)
wrappedFactory.setDest(self.dest)
d = clientEndpoint.connect(wrappedFactory)
def checkProto(proto):
if proto is None:
self.deferred.cancel()
return proto
d.addCallback(checkProto)
# When the Deferred returns an IProtocol, pass it on.
d.chainDeferred(self.deferred)
示例2: HTTP11ClientProtocolPatched
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import cancel [as 别名]
class HTTP11ClientProtocolPatched(HTTP11ClientProtocol):
def request(self, request):
if self._state != 'QUIESCENT':
return fail(RequestNotSent())
self._state = 'TRANSMITTING'
_requestDeferred = maybeDeferred(request.writeTo, self.transport)
def cancelRequest(ign):
if self.timedOut:
# Request timeout was hit
self._giveUp(Failure(TimeoutError("Request took longer than %s seconds" % request.timeout)))
else:
# Explicitly cancel the request's deferred if it's still trying to
# write when this request is cancelled.
if self._state in ('TRANSMITTING', 'TRANSMITTING_AFTER_RECEIVING_RESPONSE'):
_requestDeferred.cancel()
else:
self._giveUp(Failure(CancelledError()))
self._finishedRequest = Deferred(cancelRequest)
if self.timeout > 0:
self.timedOut = False
def timeout():
self.timedOut = True
self._finishedRequest.cancel()
td = reactor.callLater(self.timeout, timeout)
#td.cancel()
#self._finishedRequest.addBoth(td.cancel) # where/how to cancel?
# Keep track of the Request object in case we need to call stopWriting
# on it.
self._currentRequest = request
self._transportProxy = TransportProxyProducer(self.transport)
self._parser = HTTPClientParser(request, self._finishResponse)
self._parser.makeConnection(self._transportProxy)
self._responseDeferred = self._parser._responseDeferred
def cbRequestWrotten(ignored):
if self._state == 'TRANSMITTING':
self._state = 'WAITING'
self._responseDeferred.chainDeferred(self._finishedRequest)
def ebRequestWriting(err):
if self._state == 'TRANSMITTING':
self._state = 'GENERATION_FAILED'
self.transport.loseConnection()
self._finishedRequest.errback(
Failure(RequestGenerationFailed([err])))
else:
log.err(err, 'Error writing request, but not in valid state '
'to finalize request: %s' % self._state)
_requestDeferred.addCallbacks(cbRequestWrotten, ebRequestWriting)
return self._finishedRequest
示例3: testControlReadvarExchangeEmptyStatusSet
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import cancel [as 别名]
def testControlReadvarExchangeEmptyStatusSet(self):
def final(result):
self.assertEqual(self.protocol.status, STATE_UNKNOWN)
d = Deferred()
d.addBoth(final)
self.protocol.d = d
self.protocol.controlReadvarExchange()
d.cancel()
return d
示例4: testControlReadvarExchangePop
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import cancel [as 别名]
def testControlReadvarExchangePop(self):
def final(result):
self.assertFalse(self.protocol.peersToCheck)
d = Deferred()
d.addBoth(final)
self.protocol.d = d
self.protocol.peersToCheck = self.peersToCheck
self.protocol.minPeerSource = 100 # wrong value (too high)
self.protocol.controlReadvarExchange()
d.cancel()
示例5: AsyncHttpJsonClient
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import cancel [as 别名]
class AsyncHttpJsonClient(object):
'''
Supports json request payload on both HTTP GET and POST
'''
def __init__(self, **kwargs):
# uri, method, body
for k,v in kwargs.items():
setattr(self, k, v)
if not kwargs.has_key('body'):
self.body = None
else:
self.body = JsonBodyProducer(self.body)
if not kwargs.has_key('method'):
self.method = 'GET'
if not kwargs.has_key('connectTimeout'):
self.connectTimeout = 3.0
self.agent = Agent(reactor, connectTimeout=self.connectTimeout)
self.__d_agent = self.agent.request(
self.method,
self.uri,
Headers({
'User-Agent': ['AsyncHttpJsonRequest'],
'Content-Type': ['application/json'],
'Accept-Encoding': ['gzip']
}),
self.body)
self.__deferredResponse = Deferred()
def __readResponseCallback(self, response, userCb, *cbargs):
response.deliverBody(AsyncHttpResponseProtocol(self.__deferredResponse, response.headers))
self.__deferredResponse.addCallback(userCb, *([response]+list(cbargs)))
return self.__deferredResponse
def __readErrorCallback(self, error, userCb, *cbargs):
self.__deferredResponse.addErrback(userCb, *cbargs)
def addResponseCallback(self, callback, *cbargs):
self.__d_agent.addCallback(self.__readResponseCallback, callback, *cbargs)
def addResponseErrback(self, callback, *cbargs):
self.__d_agent.addErrback(self.__readErrorCallback, callback, *cbargs)
def cancelRequest(self):
try:
self.__deferredResponse.cancel()
self.__d_agent.cancel()
except Exception,e:
logger.debug(str(e))
示例6: testStartProtocolConnected
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import cancel [as 别名]
def testStartProtocolConnected(self):
def final(err):
# err is a Failure instance because of d.cancel()
if self.protocol.timeoutCall.active():
self.protocol.timeoutCall.cancel()
self.assertTrue(self.protocol.transport.connected)
d = Deferred()
d.addBoth(final)
self.protocol.d = d
self.protocol.startProtocol()
d.cancel()
return d
示例7: testSendReadStatRequestSent
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import cancel [as 别名]
def testSendReadStatRequestSent(self):
def final(err):
# err is a Failure instance because of d.cancel()
if self.protocol.timeoutCall.active():
self.protocol.timeoutCall.cancel()
self.assertTrue(self.protocol.transport.written)
d = Deferred()
d.addBoth(final)
self.protocol.d = d
self.protocol.sendReadstatRequest()
d.cancel()
return d
示例8: testSendReadStatRequestCorrect
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import cancel [as 别名]
def testSendReadStatRequestCorrect(self):
def final(err):
# err is a Failure instance because of d.cancel()
if self.protocol.timeoutCall.active():
self.protocol.timeoutCall.cancel()
written_data = self.protocol.transport.written[-1][0]
expected_data = '\x16\x01\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00'
self.assertEqual(written_data, expected_data)
d = Deferred()
d.addBoth(final)
self.protocol.d = d
self.protocol.sendReadstatRequest()
d.cancel()
return d
示例9: test_cancelledDeferred
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import cancel [as 别名]
def test_cancelledDeferred(self):
app = self.app
request = requestMock(b"/")
inner_d = Deferred()
@app.route("/")
def root(request):
return inner_d
d = _render(self.kr, request)
inner_d.cancel()
self.assertFired(d)
self.flushLoggedErrors(CancelledError)
示例10: testControlReadvarExchangePeerSet
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import cancel [as 别名]
def testControlReadvarExchangePeerSet(self):
def final(err):
# err is a Failure instance because of d.cancel()
if self.protocol.timeoutCall.active():
self.protocol.timeoutCall.cancel()
self.assertEqual(self.protocol.currentPeer, self.peer)
d = Deferred()
d.addBoth(final)
self.protocol.d = d
self.protocol.peersToCheck = self.peersToCheck
self.protocol.controlReadvarExchange()
d.cancel()
return d
示例11: ConsumerQueue
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import cancel [as 别名]
class ConsumerQueue(object):
def __init__(self, stop_on_error=False, empty=None):
self.stop_on_error = stop_on_error
self.empty = empty
self.queue = DeferredQueue()
self.size = 0
self.running = True
self._deferred = Deferred()
def _consume_next(self, *args):
if not self.running:
return
self._deferred = self.queue.get()
self._deferred.addCallbacks(self._consumer, self._error)
def _consumer(self, item):
self.size -= 1
r = self.consume(item)
if self.size == 0 and self.empty is not None:
self.empty()
if isinstance(r, Deferred):
r.addCallbacks(self._consume_next, self._consume_next)
else:
self._consume_next()
def _error(self, fail):
self.error(fail)
if not self.stop_on_error:
self._consume_next()
def add(self, item):
self.size += 1
self.queue.put(item)
def consume(self, item):
raise NotImplementedError
def error(self, fail):
raise NotImplementedError
def start(self):
self.running = True
self._consume_next()
def stop(self):
self.running = False
self._deferred.cancel()
示例12: cancel
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import cancel [as 别名]
def cancel(self):
# to signal _inlineCallbacks to not fire self.errback with CancelledError;
# otherwise we'd have to call `Deferred.cancel(self)` immediately, but it
# would be semantically unnice if, by the time the coroutine is told to do
# its clean-up routine, the inner Deferred hadn't yet actually been cancelled.
self.cancelling = True
# the _swallow_cancelled_error errback is added as the last one, so anybody else who is already listening for
# CancelledError will still get it.
if self.depends_on:
self.depends_on.addErrback(_swallow_cancelled_error)
self.depends_on.cancel()
del self.depends_on
self.addErrback(_swallow_cancelled_error)
Deferred.cancel(self)
示例13: testSendReadvarRequestCorrect
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import cancel [as 别名]
def testSendReadvarRequestCorrect(self):
def final(err):
# err is a Failure instance because of d.cancel()
if self.protocol.timeoutCall.active():
self.protocol.timeoutCall.cancel()
written_data = self.protocol.transport.written[-1][0]
expected_data = '\x16\x02\x00\x02\x00\x00g\xf3\x00\x00\x00\x06offset\x00\x00\x00\x00\x00\x00'
self.assertEqual(written_data, expected_data)
d = Deferred()
d.addBoth(final)
self.protocol.d = d
self.protocol.currentPeer = self.peer
self.protocol.sequenceCounter = 2
self.protocol.sendReadvarRequest()
d.cancel()
return d
示例14: test_cancelledDeferred
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import cancel [as 别名]
def test_cancelledDeferred(self):
app = self.app
request = requestMock("/")
inner_d = Deferred()
@app.route("/")
def root(request):
return inner_d
d = _render(self.kr, request)
inner_d.cancel()
def _cb(result):
self.assertIdentical(result, None)
self.flushLoggedErrors(CancelledError)
d.addCallback(_cb)
return d
示例15: fetch_next
# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import cancel [as 别名]
def fetch_next(self, wait=True):
timeout = Cursor._wait_to_timeout(wait)
deadline = None if timeout is None else time.time() + timeout
def wait_canceller(d):
d.errback(ReqlTimeoutError())
while len(self.items) == 0 and self.error is None:
self._maybe_fetch_batch()
wait = Deferred(canceller=wait_canceller)
self.waiting.append(wait)
if deadline is not None:
timeout = max(0, deadline - time.time())
reactor.callLater(timeout, lambda: wait.cancel())
yield wait
returnValue(not self._is_empty() or self._has_error())