当前位置: 首页>>代码示例>>Python>>正文


Python Deferred.callback方法代码示例

本文整理汇总了Python中twisted.internet.defer.Deferred.callback方法的典型用法代码示例。如果您正苦于以下问题:Python Deferred.callback方法的具体用法?Python Deferred.callback怎么用?Python Deferred.callback使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.internet.defer.Deferred的用法示例。


在下文中一共展示了Deferred.callback方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import callback [as 别名]
class Engine:
    def __init__(self, controller):
        self._ctrl = controller
        self._ctrl.add_engine(self)
        self.deferred = Deferred()

    def _signal(self, name, *args, **keywords):
        self._ctrl.signal(name, *args, **keywords)

    def __stop(self):
        self._ctrl.remove_engine(self)

    def _success(self, result=None):
        self.__stop()
        self.deferred.callback(result)

    def _failure(self, fail='Engine failed'):
        self.__stop()
        self.deferred.errback(fail)

    def abort(self):
        """Aborts this engine, does not emit a signal."""
        self.__stop()

    def send(self, something):
        return self._ctrl.send(something)

    def sendall(self, something):
        return self._ctrl.sendall(something)
开发者ID:serpent-project,项目名称:serpent,代码行数:31,代码来源:engine.py

示例2: TestBase

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import callback [as 别名]
class TestBase(object):
    def __init__(self, conn, iTag, testType):
        self._conn = conn
        self._iTag = iTag
        self._testType = testType

        self._data = []

    def _activate(self):
        pass

    def _deactivate(self):
        pass

    def _run(self):
        raise NotImplementedError

    def run(self, _):
        self._deferred = Deferred()
        self._conn.reactor.callLater(1, self._activate)
        self._conn.reactor.callLater(2, self._run)
        return self._deferred

    def _done(self):
        self._deactivate()
        self._deferred.callback(None)

    def __str__(self):
        return json.dumps({'type' : self._testType, 'data' : self._data})
开发者ID:vmayoral,项目名称:rce,代码行数:31,代码来源:base.py

示例3: get_package

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import callback [as 别名]
    def get_package(self, request, from_ip=None):
        commands = self._parse_request(request)

        d = Deferred()

        d.callback(commands)
        return d
开发者ID:inkhey,项目名称:mmc,代码行数:9,代码来源:endpoints.py

示例4: test_deferPreCommit

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import callback [as 别名]
 def test_deferPreCommit(self):
     """
     If callables passed to L{IAsyncTransaction.preCommit} return
     L{Deferred}s, they will defer the actual commit operation until it has
     fired.
     """
     txn = self.createTransaction()
     d = Deferred()
     def wait():
         wait.started = True
         def executed(it):
             wait.sqlResult = it
         # To make sure the _underlying_ commit operation was Deferred, we
         # have to execute some SQL to make sure it happens.
         return (d.addCallback(lambda ignored: txn.execSQL("some test sql"))
                  .addCallback(executed))
     wait.started = False
     wait.sqlResult = None
     txn.preCommit(wait)
     result = self.resultOf(txn.commit())
     self.flushHolders()
     self.assertEquals(wait.started, True)
     self.assertEquals(wait.sqlResult, None)
     self.assertEquals(result, [])
     d.callback(None)
     # allow network I/O for pooled / networked implementation; there should
     # be the commit message now.
     self.flushHolders()
     self.assertEquals(len(result), 1)
     self.assertEquals(wait.sqlResult, [[1, "some test sql"]])
开发者ID:anemitz,项目名称:calendarserver,代码行数:32,代码来源:test_adbapi2.py

示例5: test_double_subscribe

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import callback [as 别名]
        def test_double_subscribe(self):
            handler = ApplicationSession()
            MockTransport(handler)

            event0 = Deferred()
            event1 = Deferred()

            subscription0 = yield handler.subscribe(
                lambda: event0.callback(42), u'com.myapp.topic1')
            subscription1 = yield handler.subscribe(
                lambda: event1.callback('foo'), u'com.myapp.topic1')
            # same topic, same ID
            self.assertTrue(subscription0.id == subscription1.id)

            # do a publish (MockTransport fakes the acknowledgement
            # message) and then do an actual publish event. The IDs
            # are the same, so we just do one Event.
            publish = yield handler.publish(
                u'com.myapp.topic1',
                options=types.PublishOptions(acknowledge=True, exclude_me=False),
            )
            handler.onMessage(message.Event(subscription0.id, publish.id))

            # ensure we actually got both callbacks
            self.assertTrue(event0.called, "Missing callback")
            self.assertTrue(event1.called, "Missing callback")
开发者ID:Hrabal,项目名称:autobahn-python,代码行数:28,代码来源:test_protocol.py

示例6: testTriggerSystemEvent3

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import callback [as 别名]
 def testTriggerSystemEvent3(self):
     # make sure reactor can survive the loss of an event type while
     # waiting for a before-trigger's Deferred to fire
     l = []
     d = Deferred()
     d2 = Deferred()
     def _returnDeferred(d=d):
         return d
     def _appendToList(l=l):
         l.append(1)
     def _ignore(failure):
         return None
     r = reactor
     b1 = self.addTrigger("before", "defer3", _returnDeferred)
     b2 = self.addTrigger("after", "defer3", _appendToList)
     r.fireSystemEvent("defer3")
     self.assertEquals(len(l), 0, "Event should not have fired yet.")
     self.removeTrigger(b1)
     self.removeTrigger(b2)
     try:
         d.callback(None) # cReactor gives errback to deferred
     except ValueError:
         pass
     self.assertEquals(len(l), 0)
     d.addErrback(_ignore)
开发者ID:KatiaBorges,项目名称:exeLearning,代码行数:27,代码来源:test_internet.py

示例7: testTriggerSystemEvent2

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import callback [as 别名]
 def testTriggerSystemEvent2(self):
     # one of the "before" trigger functions returns a deferred. A later
     # "before" trigger fires the deferred. A third before runs. Then a
     # "during" should be run. One of the failure modes for the old
     # cReactor code is to start the "during" as soon as the deferred
     # fires, rather than waiting for the "before" phase to be finished
     l = []
     d = Deferred()
     d2 = Deferred()
     def _returnDeferred(d=d):
         return d
     def _fireDeferred(d=d):
         d.callback(None)
     def _returnDeferred2(d2=d2):
         return d2
     def _appendToList(l=l):
         l.append(1)
     r = reactor
     # to test this properly, the triggers must fire in this sequence:
     # _returnDeferred, _fireDeferred, _returnDeferred2 . cReactor happens
     # to run triggers in the order in which they were added.
     self.addTrigger("before", "defer2", _returnDeferred)
     self.addTrigger("before", "defer2", _fireDeferred)
     self.addTrigger("before", "defer2", _returnDeferred2)
     self.addTrigger("during", "defer2", _appendToList)
     self.addTrigger("after", "defer2", _appendToList)
     r.fireSystemEvent("defer2")
     self.assertEquals(len(l), 0, "Event should not have fired yet.")
     d2.callback(None)
     self.assertEquals(len(l), 2)
开发者ID:KatiaBorges,项目名称:exeLearning,代码行数:32,代码来源:test_internet.py

示例8: _Producer

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import callback [as 别名]
class _Producer(object):
    implements(IPullProducer)

    deferred = None

    def __init__(self, body, consumer):
        """:param body: an iterable of strings"""

        # check to see if we can determine the length
        try:
            len(body) # iterator?
            self.length = sum([len(fragment) for fragment in body])
            self.body = iter(body)

        except TypeError:
            self.length = UNKNOWN_LENGTH
            self.body = body

        self.deferred = Deferred()

        self.consumer = consumer

    def resumeProducing(self):
        try:
            chunk = self.body.next()

        except StopIteration, e:
            self.consumer.unregisterProducer()
            if self.deferred is not None:
                self.deferred.callback(self.consumer)
                self.deferred = None
            return

        self.consumer.write(chunk)
开发者ID:amgibson,项目名称:spyne,代码行数:36,代码来源:twisted.py

示例9: noop

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import callback [as 别名]
def noop(id, data, config, runsettings):
    """
    Do nothing
    """
    d = Deferred()
    d.callback(True)
    return d
开发者ID:DefaultUser,项目名称:PyTIBot,代码行数:9,代码来源:__init__.py

示例10: SubprocessProtocol

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import callback [as 别名]
class SubprocessProtocol(protocol.ProcessProtocol):
    """Twisted-friendly subprocess."""
    
    def __init__(self, args, environment):
        self.deferred = Deferred()
        self.buffer = StringIO()
        
        reactor.spawnProcess(self, args[0], args, self.clean_environ(environment))
    
    def outReceived(self, data):
        self.buffer.write(data)
    
    def errReceived(self, data):
        self.outReceived(data)
    
    def processEnded(self, status):
        self.deferred.callback(self.buffer.getvalue())
    
    @staticmethod
    def clean_environ(environ):
        """Filter non-string items from environ, as reactor.spawnProcess cannot handle them."""
        
        for k, v in environ.items():
            if type(v) not in [str, unicode]:
                environ.pop(k)
        
        return environ
开发者ID:Thatonesexyguy,项目名称:gadget,代码行数:29,代码来源:Commands.py

示例11: WebSocketConnection

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import callback [as 别名]
class WebSocketConnection(WebSocketProtocol):
	def __init__(self, stateObject):
		self.state = stateObject
		self.opcode = TEXT
		WebSocketProtocol.__init__(self, WebSocketReceiver(self))
		self.finished = Deferred()
		self.pingLoop = LoopingCall(self.doPing)

	def doPing(self):
		self.receiver.transport.sendFrame(PING, '')

	def write(self, data):
		self.receiver.transport.sendFrame(self.opcode, data)

	def sendFrame(self, opcode, data):
		self.receiver.transport.sendFrame(opcode, data)

	def writeSequence(self, data):
		for chunk in data:
			self.write(chunk)

	def connectionLost(self, reason):
		if self.pingLoop.running:
			self.pingLoop.stop()
		self.finished.callback(self)
开发者ID:intangere,项目名称:Essence,代码行数:27,代码来源:server.py

示例12: test_producer_cancel_one_request_getting_topic

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import callback [as 别名]
    def test_producer_cancel_one_request_getting_topic(self):
        # Test cancelling a request after it's begun to be processed
        client = Mock()
        client.topic_partitions = {}
        ret = Deferred()
        client.load_metadata_for_topics.return_value = ret
        msgs = [self.msg("one"), self.msg("two")]
        msgs2 = [self.msg("three"), self.msg("four")]
        batch_n = 4

        producer = Producer(client, batch_every_n=batch_n, batch_send=True)
        d1 = producer.send_messages(self.topic, msgs=msgs)
        # Check that no request was sent
        self.assertFalse(client.send_produce_request.called)
        # This will trigger the metadata lookup
        d2 = producer.send_messages(self.topic, msgs=msgs2)
        d1.cancel()
        self.failureResultOf(d1, CancelledError)
        # Check that still no request was sent
        self.assertFalse(client.send_produce_request.called)
        self.assertNoResult(d2)
        # Setup the client's topics and trigger the metadata deferred
        client.topic_partitions = {self.topic: [0, 1, 2, 3]}
        client.metadata_error_for_topic.return_value = False
        ret.callback(None)
        # Expect that only the msgs2 messages were sent
        msgSet = create_message_set(
            make_send_requests(msgs2), producer.codec)
        req = ProduceRequest(self.topic, 1, msgSet)
        client.send_produce_request.assert_called_once_with(
            [req], acks=producer.req_acks, timeout=producer.ack_timeout,
            fail_on_error=False)

        producer.stop()
开发者ID:joshainglis,项目名称:afkak,代码行数:36,代码来源:test_producer.py

示例13: test_producer_send_messages_no_acks

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import callback [as 别名]
    def test_producer_send_messages_no_acks(self):
        first_part = 19
        client = Mock()
        ret = Deferred()
        client.send_produce_request.return_value = ret
        client.topic_partitions = {self.topic: [first_part, 101, 102, 103]}
        client.metadata_error_for_topic.return_value = False
        msgs = [self.msg("one"), self.msg("two")]
        ack_timeout = 5

        producer = Producer(client, ack_timeout=ack_timeout,
                            req_acks=PRODUCER_ACK_NOT_REQUIRED)
        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, first_part, msgSet)
        client.send_produce_request.assert_called_once_with(
            [req], acks=producer.req_acks, timeout=ack_timeout,
            fail_on_error=False)
        # Check results when "response" fires
        self.assertNoResult(d)
        ret.callback([])
        result = self.successResultOf(d)
        self.assertEqual(result, None)
        producer.stop()
开发者ID:joshainglis,项目名称:afkak,代码行数:28,代码来源:test_producer.py

示例14: sync_box

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import callback [as 别名]
    def sync_box(self, root_box):
        """ Start syncing the named box. """
        logging.debug("WebServer, sync_box for root_box {0}".format(root_box))
        return_d = Deferred()

        if root_box in self.syncs:
            logging.error("sync_box: returning from cache")
            indxsync = self.syncs[root_box]
            return_d.callback(indxsync)
        else:
            def err_cb(failure):
                logging.error("WebServer, sync_box error getting token: {0} {1}".format(failure, failure.value))
                # FIXME do something with the error?
                return_d.errback(failure)

            self.syncs[root_box] = None # reserve the slot

            def store_cb(root_store):
                indxsync = IndxSync(root_store, self.database, self.server_url, self.keystore, self)
                self.syncs[root_box] = indxsync
                return_d.callback(indxsync)

            # assign ourselves a new token to access the root box using the @indx user
            # this only works because the "create_root_box" function gave this user read permission
            # this doesn't work in the general case.
            def token_cb(token):
                token.get_store().addCallbacks(store_cb, err_cb)

            self.tokens.new("@indx","",root_box,"IndxSync","/","::1", self.server_id).addCallbacks(token_cb, return_d.errback)

        return return_d 
开发者ID:sociam,项目名称:indx,代码行数:33,代码来源:server.py

示例15: test_subsequentBeforeTriggerFiresPriorBeforeDeferred

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import callback [as 别名]
 def test_subsequentBeforeTriggerFiresPriorBeforeDeferred(self):
     """
     If a trigger added to the C{'before'} phase of an event calls back a
     L{Deferred} returned by an earlier trigger in the C{'before'} phase of
     the same event, the remaining C{'before'} triggers for that event
     should be run and any further L{Deferred}s waited on before proceeding
     to the C{'during'} events.
     """
     eventType = 'test'
     events = []
     firstDeferred = Deferred()
     secondDeferred = Deferred()
     def firstBeforeTrigger():
         return firstDeferred
     def secondBeforeTrigger():
         firstDeferred.callback(None)
     def thirdBeforeTrigger():
         events.append('before')
         return secondDeferred
     def duringTrigger():
         events.append('during')
     self.addTrigger('before', eventType, firstBeforeTrigger)
     self.addTrigger('before', eventType, secondBeforeTrigger)
     self.addTrigger('before', eventType, thirdBeforeTrigger)
     self.addTrigger('during', eventType, duringTrigger)
     self.assertEqual(events, [])
     reactor.fireSystemEvent(eventType)
     self.assertEqual(events, ['before'])
     secondDeferred.callback(None)
     self.assertEqual(events, ['before', 'during'])
开发者ID:Alberto-Beralix,项目名称:Beralix,代码行数:32,代码来源:test_internet.py


注:本文中的twisted.internet.defer.Deferred.callback方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。