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


Python Future.add_done_callback方法代码示例

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


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

示例1: _start_processing_requests

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import add_done_callback [as 别名]
    def _start_processing_requests(self):
        while True:
            data = yield gen.Task(self._stream.read_until, '\r\n')
            log.debug('New request: %r', data)
            try:
                msg = json.loads(data)
                key = msg['key']
                method = msg['method']
                args = msg['args']
                kwargs = msg['kwargs']
            except (KeyError, ValueError):
                log.error('Malformed request data: %s', data)
                continue
            try:
                res = self._handler(method, *args, **kwargs)
                if isinstance(res, Future):
                    future = res
                else:
                    future = Future()
                    future.set_result(res)
            except Exception as e:
                log.exception('Failed to handle request: %s', key)
                future = concurrent.TracebackFuture()
                future.set_exception(e)

            future.add_done_callback(partial(self._on_future_finished, key))
开发者ID:EverythingMe,项目名称:snakepit,代码行数:28,代码来源:server.py

示例2: put_task

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import add_done_callback [as 别名]
 def put_task(self, inputs, callback=None):
     """ return a Future of output."""
     f = Future()
     if callback is not None:
         f.add_done_callback(callback)
     self.input_queue.put((inputs, f))
     return f
开发者ID:rightwaitforyou,项目名称:tensorpack,代码行数:9,代码来源:concurrency.py

示例3: _get_conn

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import add_done_callback [as 别名]
    def _get_conn(self):  # -> Future[connection]
        now = self.io_loop.time()

        # Try to reuse in free pool
        while self._free_conn:
            conn = self._free_conn.popleft()
            if now - conn.connected_time > self.max_recycle_sec:
                self._close_async(conn)
                continue
            log.debug("Reusing connection from pool: %s", self.stat())
            fut = Future()
            fut.set_result(conn)
            return fut

        # Open new connection
        if self.max_open == 0 or self._opened_conns < self.max_open:
            self._opened_conns += 1
            log.debug("Creating new connection: %s", self.stat())
            fut = connect(**self.connect_kwargs)
            fut.add_done_callback(self._on_connect)  # self._opened_conns -=1 on exception
            return fut

        # Wait to other connection is released.
        fut = Future()
        self._waitings.append(fut)
        return fut
开发者ID:PyMySQL,项目名称:Tornado-MySQL,代码行数:28,代码来源:pools.py

示例4: ManualCapClient

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import add_done_callback [as 别名]
class ManualCapClient(BaseCapClient):
    def capitalize(self, request_data, callback=None):
        logging.debug("capitalize")
        self.request_data = request_data
        self.stream = IOStream(socket.socket())
        self.stream.connect(('127.0.0.1', self.port),
                            callback=self.handle_connect)
        self.future = Future()
        if callback is not None:
            self.future.add_done_callback(
                stack_context.wrap(lambda future: callback(future.result())))
        return self.future

    def handle_connect(self):
        logging.debug("handle_connect")
        self.stream.write(utf8(self.request_data + "\n"))
        self.stream.read_until(b'\n', callback=self.handle_read)

    def handle_read(self, data):
        logging.debug("handle_read")
        self.stream.close()
        try:
            self.future.set_result(self.process_response(data))
        except CapError as e:
            self.future.set_exception(e)
开发者ID:alexdxy,项目名称:tornado,代码行数:27,代码来源:concurrent_test.py

示例5: wait

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import add_done_callback [as 别名]
    def wait(self, timeout: Union[float, datetime.timedelta] = None) -> "Future[None]":
        """Block until the internal flag is true.

        Returns a Future, which raises `tornado.util.TimeoutError` after a
        timeout.
        """
        fut = Future()  # type: Future[None]
        if self._value:
            fut.set_result(None)
            return fut
        self._waiters.add(fut)
        fut.add_done_callback(lambda fut: self._waiters.remove(fut))
        if timeout is None:
            return fut
        else:
            timeout_fut = gen.with_timeout(
                timeout, fut, quiet_exceptions=(CancelledError,)
            )
            # This is a slightly clumsy workaround for the fact that
            # gen.with_timeout doesn't cancel its futures. Cancelling
            # fut will remove it from the waiters list.
            timeout_fut.add_done_callback(
                lambda tf: fut.cancel() if not fut.done() else None
            )
            return timeout_fut
开发者ID:rgbkrk,项目名称:tornado,代码行数:27,代码来源:locks.py

示例6: acquire

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import add_done_callback [as 别名]
    def acquire(
        self, timeout: Union[float, datetime.timedelta] = None
    ) -> "Future[_ReleasingContextManager]":
        """Decrement the counter. Returns a Future.

        Block if the counter is zero and wait for a `.release`. The Future
        raises `.TimeoutError` after the deadline.
        """
        waiter = Future()  # type: Future[_ReleasingContextManager]
        if self._value > 0:
            self._value -= 1
            waiter.set_result(_ReleasingContextManager(self))
        else:
            self._waiters.append(waiter)
            if timeout:

                def on_timeout() -> None:
                    if not waiter.done():
                        waiter.set_exception(gen.TimeoutError())
                    self._garbage_collect()

                io_loop = ioloop.IOLoop.current()
                timeout_handle = io_loop.add_timeout(timeout, on_timeout)
                waiter.add_done_callback(
                    lambda _: io_loop.remove_timeout(timeout_handle)
                )
        return waiter
开发者ID:rgbkrk,项目名称:tornado,代码行数:29,代码来源:locks.py

示例7: fetch

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import add_done_callback [as 别名]
    def fetch(self, request, callback=None, raise_error=True, **kwargs):
        if not isinstance(request, HTTPRequest):
            request = HTTPRequest(url=request, **kwargs)

        key = self.cache.create_key(request)

        # Check and return future if there is a pending request
        pending = self.pending_requests.get(key)
        if pending:
            return pending

        response = self.cache.get_response_and_time(key)
        if response:
            response.cached = True
            if callback:
                self.io_loop.add_callback(callback, response)
            future = Future()
            future.set_result(response)
            return future

        future = orig_fetch(self, request, callback, raise_error, **kwargs)

        self.pending_requests[key] = future

        def cache_response(future):
            exc = future.exception()
            if exc is None:
                self.cache.save_response(key, future.result())

        future.add_done_callback(cache_response)
        return future
开发者ID:ByteInternet,项目名称:tornado-client-cache,代码行数:33,代码来源:tornado_client_cache.py

示例8: send_message

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import add_done_callback [as 别名]
    def send_message(self, args, callback=None):

        command = args[0]

        if 'SUBSCRIBE' in command:
            raise NotImplementedError('Not yet.')

        # Do not allow the commands, affecting the execution of other commands,
        # to be used on shared connection.
        if command in ('WATCH', 'MULTI'):
            if self.is_shared():
                raise Exception('Command %s is not allowed while connection '
                                'is shared!' % command)
            if command == 'WATCH':
                self._watch.add(args[1])
            if command == 'MULTI':
                self._multi = True

        # monitor transaction state, to unlock correctly
        if command in ('EXEC', 'DISCARD', 'UNWATCH'):
            if command in ('EXEC', 'DISCARD'):
                self._multi = False
            self._watch.clear()

        self.stream.write(self.format_message(args))

        future = Future()

        if callback is not None:
            future.add_done_callback(stack_context.wrap(callback))

        self.callbacks.append(future.set_result)

        return future
开发者ID:ei-grad,项目名称:toredis,代码行数:36,代码来源:client.py

示例9: wrapper

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import add_done_callback [as 别名]
	def wrapper(*args, **kwargs):
		future = Future()
		callback, args, kwargs = replacer.replace(future, args, kwargs)
		if callback is not None:
			future.add_done_callback(
				functools.partial(_auth_future_to_callback, callback))
		f(*args, **kwargs)
		return future
开发者ID:auscompgeek,项目名称:perfectgift,代码行数:10,代码来源:auth.py

示例10: register

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import add_done_callback [as 别名]
 def register(self, name, callback=None):
     msg_id = next(self._generator)
     buf = self._pack_request(msg_id, RPC_REGISTER, 'register', (name))
     future = Future()
     if callback:
         future.add_done_callback(callback)
     self.add_request_table(msg_id, future)
     self.write(buf)
     return future
开发者ID:yoki123,项目名称:torpc,代码行数:11,代码来源:rpc.py

示例11: put_task

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import add_done_callback [as 别名]
 def put_task(self, dp, callback=None):
     """
     dp must be non-batched, i.e. single instance
     """
     f = Future()
     if callback is not None:
         f.add_done_callback(callback)
     self.input_queue.put((dp, f))
     return f
开发者ID:singlepetrol,项目名称:tensorpack,代码行数:11,代码来源:concurrency.py

示例12: put_task

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import add_done_callback [as 别名]
 def put_task(self, dp, callback=None):
     """
     Same as in :meth:`AsyncPredictorBase.put_task`.
     """
     f = Future()
     if callback is not None:
         f.add_done_callback(callback)
     self.input_queue.put((dp, f))
     return f
开发者ID:quanlzheng,项目名称:tensorpack,代码行数:11,代码来源:concurrency.py

示例13: fetch

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import add_done_callback [as 别名]
    def fetch(self, request, callback=None, raise_error=True, **kwargs):
        """Executes a request, asynchronously returning an `HTTPResponse`.

        The request may be either a string URL or an `HTTPRequest` object.
        If it is a string, we construct an `HTTPRequest` using any additional
        kwargs: ``HTTPRequest(request, **kwargs)``

        This method returns a `.Future` whose result is an
        `HTTPResponse`. By default, the ``Future`` will raise an
        `HTTPError` if the request returned a non-200 response code
        (other errors may also be raised if the server could not be
        contacted). Instead, if ``raise_error`` is set to False, the
        response will always be returned regardless of the response
        code.

        If a ``callback`` is given, it will be invoked with the `HTTPResponse`.
        In the callback interface, `HTTPError` is not automatically raised.
        Instead, you must check the response's ``error`` attribute or
        call its `~HTTPResponse.rethrow` method.
        """
        if self._closed:
            raise RuntimeError("fetch() called on closed AsyncHTTPClient")
        if not isinstance(request, HTTPRequest):
            request = HTTPRequest(url=request, **kwargs)
        else:
            if kwargs:
                raise ValueError("kwargs can't be used if request is an HTTPRequest object")
        # We may modify this (to add Host, Accept-Encoding, etc),
        # so make sure we don't modify the caller's object.  This is also
        # where normal dicts get converted to HTTPHeaders objects.
        request.headers = httputil.HTTPHeaders(request.headers)
        request = _RequestProxy(request, self.defaults)
        future = Future()
        if callback is not None:
            callback = stack_context.wrap(callback)

            def handle_future(future):
                exc = future.exception()
                if isinstance(exc, HTTPError) and exc.response is not None:
                    response = exc.response
                elif exc is not None:
                    response = HTTPResponse(
                        request, 599, error=exc,
                        request_time=time.time() - request.start_time)
                else:
                    response = future.result()
                self.io_loop.add_callback(callback, response)
            future.add_done_callback(handle_future)

        def handle_response(response):
            if raise_error and response.error:
                future.set_exception(response.error)
            else:
                future_set_result_unless_cancelled(future, response)
        self.fetch_impl(request, handle_response)
        return future
开发者ID:alexdxy,项目名称:tornado,代码行数:58,代码来源:httpclient.py

示例14: close

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import add_done_callback [as 别名]
 def close(self):
     if self._cursor is None:
         self._cursor.close()
         future = Future()
         future.set_result(None)
     else:
         future = async_call_method(self._cursor.close)
     self._cursor = None
     future.add_done_callback(self._release_lock)
     return future
开发者ID:mosquito,项目名称:mytor,代码行数:12,代码来源:cursor.py

示例15: put_task

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import add_done_callback [as 别名]
 def put_task(self, inputs, callback=None):
     """
     :params inputs: a data point (list of component) matching input_names (not batched)
     :params callback: a callback to get called with the list of outputs
     :returns: a Future of output."""
     f = Future()
     if callback is not None:
         f.add_done_callback(callback)
     self.input_queue.put((inputs, f))
     return f
开发者ID:rahulbprakash,项目名称:tensorpack,代码行数:12,代码来源:concurrency.py


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