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


Python Deferred.addCallbacks方法代码示例

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


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

示例1: _startDTrace

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallbacks [as 别名]
 def _startDTrace(self, pid):
     started = Deferred()
     stopped = Deferred()
     process = reactor.spawnProcess(
         IOMeasureConsumer(started, stopped, _DTraceParser(self)),
         "/usr/sbin/dtrace",
         ["/usr/sbin/dtrace",
          # process preprocessor macros
          "-C",
          # search for include targets in the source directory containing this file
          "-I", dirname(__file__),
          # suppress most implicitly generated output (which would mess up our parser)
          "-q",
          # make this pid the target
          "-p", str(pid),
          # load this script
          "-s", self._dScript])
     def eintr(reason):
         reason.trap(DTraceBug)
         print 'Dtrace startup failed (', reason.getErrorMessage().strip(), '), retrying.'
         return self._startDTrace(pid)
     def ready(passthrough):
         # Once the dtrace process is ready, save the state and
         # have the stopped Deferred deal with the results.  We
         # don't want to do either of these for failed dtrace
         # processes.
         self.dtraces[pid] = process
         stopped.addCallback(self._cleanup, pid)
         return passthrough
     started.addCallbacks(ready, eintr)
     return started, stopped
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:33,代码来源:benchmark.py

示例2: getRemoteResult

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallbacks [as 别名]
 def getRemoteResult(self, jobid, mapid, partition_number, put):
     d = Deferred()
     collector = SimplePageCollector(d, put)
     d.addCallbacks(self.ok, self.nok)
     #return self.kvreferenceable.callRemote("getResult", collector, jobid, mapid, partition_number)
     self.kvreferenceable.callRemote("getResult", collector, jobid, mapid, partition_number)
     return d
开发者ID:antoniobarbuzzi,项目名称:PyTxMR,代码行数:9,代码来源:kvstuff.py

示例3: Manager

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

    """The manager object receives all the events and forwards them to the
    interested objects.
    """
    
    def __init__(self):
        self.listeners = WeakKeyDictionary()
        self.eventQueue = Deferred() # Uses a deferred object to handle the
                                     # queueing of events
        self.eventQueue.callback(1) # kick-off the queue on initialization
                                       # so it attempts to run the next job
                                       # whenever it can
    
    def register(self, listener):
        assert isinstance(listener, Listener), "Only classes inheriting from \
the Listener base-class can register with the manager as a listener"
        self.listeners[listener] = 1
        
    def queueEvent(self, event):
        self.eventQueue.addCallbacks(self.post, self.printError, (event,) )
    
    def post(self, __, event):
        """This method is designed to be queued in a deferred object, so its
        first parameter is ignored, and its return in None, because the return
        of a callback in a deferred is passed in as the first parameter of the
        next callback method, so posts can be chained together in the
        eventQueue deferred indefinitely."""
        for listener in self.listeners.keys():
            listener.getEvent(event)
        return 1
        
    def printError(self, fail):
        print fail.getTraceback()
        fail.trap(RuntimeError)
开发者ID:jdbecker,项目名称:Beardo,代码行数:37,代码来源:manager.py

示例4: join

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallbacks [as 别名]
 def join(self, _):
     def send(_, node):
         factory = NodeClientFactory(OverlayService(self), {"command" : \
                 "join","node":self.my_node})
         reactor.connectTCP(node["host"], node["tcp_port"], factory)
         factory.deferred.addCallback(lambda _: node)
         def sendcallback(_):
             return node
         def senderrback(_):
             raise Exception()
         factory.deferred.addCallbacks(sendcallback,senderrback)
         return factory.deferred
     def success(node):
         coordinator = node
     def error(e):
         self.is_coordinator = True
         self.my_node["id"] = 0
         self.nextid = 1
         self.members[self.my_node["host"]] = self.my_node
         send_log("Notice", "I am coordinator")
         return e
     # search for running loadbalancers and join the overlay network
     initialized = False
     d = Deferred()
     for node in self.config["nodes"]:
         d.addErrback(send, node)
     d.addCallbacks(success, error)
     d.errback(0)
     return d
开发者ID:henrikssn,项目名称:amazonaws,代码行数:31,代码来源:loadbalancer.py

示例5: upload

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallbacks [as 别名]
 def upload(self, fd, bucket, object_name, content_type=None,
            metadata={}, parts_generator=None, part_handler=None,
            amz_headers={}, on_part_generated=None):
     self.log.msg('Beginning upload to bucket=%s,key=%s' % (
                  bucket, object_name))
     client = self.region.get_s3_client()
     if parts_generator is None:
         parts_generator = FileIOPartsGenerator()
     if part_handler is None:
         part_handler = SingleProcessPartUploader()
     # TODO - probably need some pluggable strategy for getting the parts
     # count (if desired) or not (optimization) - maybe parts_count()
     # method on IPartsGenerator.
     # Or maybe this whole counter idea is just plain wrong.
     counter = self.counter_factory(parts_generator.count_parts(fd))
     counter.context = '[object_name=%s] ' % object_name
     part_handler.client = client
     d = Deferred()
     task = MultipartUpload(client, fd, parts_generator, part_handler,
                            counter, d, self.log)
     task.on_part_generated = on_part_generated
     task.throughput_counter = self.throughput_counter
     self.uploads.add(task)
     d.addCallbacks(self._completed_upload, self.log.err)\
         .addBoth(self._remove_upload, task)
     task.upload(bucket, object_name, content_type, metadata, amz_headers)
     return d
开发者ID:djfroofy,项目名称:bafload,代码行数:29,代码来源:up.py

示例6: exchange

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallbacks [as 别名]
        def exchange(ls, receivers):
            # Send share to all receivers.
            pc = tuple(self.program_counter)
            keyLists = []
            for other_id in receivers:
                message_string = ""
                for inx, beDOZaContents in enumerate(ls):
                    keyLists.append(beDOZaContents.get_keys())
                    message_string += "%s:%s;" % \
                           (beDOZaContents.get_value().value,
                            beDOZaContents.get_mac(other_id - 1).value)
                self.protocols[other_id].sendData(pc, TEXT, message_string)

            if self.id in receivers:
                def deserialize(s):
                    def field_long(x):
                        return field(long(x))
                    xs = s[0:-1].split(';')
                    ys = [x.split(':') for x in xs]
                    return [map(field_long, xs) for xs in ys]
                num_players = len(self.players.keys())
                values = num_players * [None]
                for inx, other_id in enumerate(self.players.keys()):
                    d = Deferred()
                    d.addCallbacks(deserialize, self.error_handler)
                    self._expect_data(other_id, TEXT, d)
                    values[inx] = d
                result = gatherResults(values)
                result.addCallbacks(recombine_value, self.error_handler,
                                    callbackArgs=(keyLists, len(shares)))
                return result
开发者ID:MaxFangX,项目名称:viff,代码行数:33,代码来源:bedoza.py

示例7: on_api_finished

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallbacks [as 别名]
                def on_api_finished(response, url):
                    """Success callback when an API response is received

                    Args:
                    response: The twisted.web.client.Response for the HTTP
                              request
                    url: The url for this API request

                    Returns:
                    A twisted.internet.defer.Deferred that is fired when the API
                        body is processed
                    A twisted.python.failure.Failure on error
                    """

                    if response.code / 100 != 2:
                        return self._create_http_failure(url, response)

                    api_finished_deferred = Deferred()

                    def on_api_body_read(api_json_body):
                        """Success callback for reading the body of an API

                        Args:
                        api_json_body: The JSON body for the API

                        Returns:
                        api_json_body
                        """
                        write_resource_file(api_json_body)
                        return api_json_body

                    api_finished_deferred.addCallbacks(on_api_body_read,
                        on_error)
                    response.deliverBody(JSONBodyReceiver(api_finished_deferred))
                    return api_finished_deferred
开发者ID:matt-jordan,项目名称:twisted-ari,代码行数:37,代码来源:swagger_client.py

示例8: test

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallbacks [as 别名]
def test():
    d = Deferred()
    d.addCallbacks(gotPoets, gotFailed)
    # traceback.print_stack()
    # d.callback('tips poetm short')
    d.errback(Exception('tips poetm shorts'))
    print "....end....."
开发者ID:flybird1971,项目名称:spiders,代码行数:9,代码来源:twisted_test.py

示例9: test1

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallbacks [as 别名]
def test1():
    d = Deferred()
    # add a callback/errback pair to the chain
    d.addCallbacks(successHandle, failedHandle)
    # fire the chain with a normal result
    d.callback('Successful')

    print "Finished test1"
开发者ID:0814jimmy,项目名称:devices_control,代码行数:10,代码来源:test_defer.py

示例10: onResponse

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallbacks [as 别名]
 def onResponse(self, resp):
     log.debug('entered wsapi:wsApiServer: onResponse')
     log.error(resp)
     headers = list(resp.headers.getAllRawHeaders())
     log.debug(headers)
     finished = Deferred()
     resp.deliverBody(wsapiResponse(finished))
     finished.addCallbacks(self.getJsonResult,self.onError)
     return finished
开发者ID:cicide,项目名称:Flex-Voicemail,代码行数:11,代码来源:wsapi.py

示例11: receive_shares

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallbacks [as 别名]
 def receive_shares(player_id):
     Cx = Deferred()
     xi = self._expect_share(player_id, field)
     rho1 = self._expect_share(player_id, field)
     rho2 = self._expect_share(player_id, field)
     self._expect_data(player_id, TEXT, Cx)
     Cx.addCallbacks(commitment.deserialize,
                     self.error_handler)
     return gatherResults([xi, rho1, rho2, Cx])
开发者ID:MaxFangX,项目名称:viff,代码行数:11,代码来源:orlandi.py

示例12: connectBox

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallbacks [as 别名]
 def connectBox(self):
     if not self.proto:
         cb = ConnectBox(self)
         if cb.exec_():
             (self.host, self.port) = cb.getValues()
             d = Deferred()
             d.addCallbacks(self.connectSuccess, self.connectFailed)
             from twisted.internet import reactor
             reactor.connectTCP(self.host, int(self.port),
                                GameClientFactory(d))
开发者ID:vanzi,项目名称:miners-game,代码行数:12,代码来源:client.py

示例13: request_deferred

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallbacks [as 别名]
def request_deferred(request):
    '''Wrap a request inside a Deferred.

    This returns a Deferred whose first pair of callbacks are the request
    callback and errback.
    '''
    d = Deferred()
    if request.callback:
        d.addCallbacks(request.callback, request.errback)
    request.callback, request.errback = d.callback, d.errback
    return d
开发者ID:Mimino666,项目名称:crawlmi,代码行数:13,代码来源:request.py

示例14: api_received

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallbacks [as 别名]
 def api_received(self, response):
     if response.code == 200 :
         result_proto = Deferred()
         result_proto.addCallbacks(self.api_succeed, self.api_failed)
         response.deliverBody(JsonDataConsumer(result_proto))
     else :
         def get_response_text(reason):
             self.api_failed(reason)
         response_defer = Deferred()
         response_defer.addBoth(get_response_text)
         response.deliverBody(TextDataConsumer(response_defer))
开发者ID:NPeganov,项目名称:devicehive-python,代码行数:13,代码来源:auto.py

示例15: main

# 需要导入模块: from twisted.internet.defer import Deferred [as 别名]
# 或者: from twisted.internet.defer.Deferred import addCallbacks [as 别名]
def main(reactor, masterIP):
    deferred = Deferred()
    
    def callback(msg):
        print(msg)
        reactor.stop()
    
    deferred.addCallbacks(callback, callback)
    
    reactor.connectTCP(masterIP, MASTER_UID_PORT, UIDClient(deferred))
    reactor.run()
开发者ID:LCROBOT,项目名称:rce,代码行数:13,代码来源:getUID.py


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