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


Python Future.set_exception方法代码示例

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


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

示例1: apply

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
 def apply(callback) -> 'promise.Promise':
     f = Future()
     try:
         f.set_result(callback())
     except BaseException as e:
         f.set_exception(e)
     return Promise(f)
开发者ID:vs223,项目名称:file-viewer,代码行数:9,代码来源:promise.py

示例2: _start_processing_requests

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [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

示例3: _create_stream

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
 def _create_stream(self, max_buffer_size, af, addr, source_ip=None,
                    source_port=None):
     # Always connect in plaintext; we'll convert to ssl if necessary
     # after one connection has completed.
     source_port_bind = source_port if isinstance(source_port, int) else 0
     source_ip_bind = source_ip
     if source_port_bind and not source_ip:
         # User required a specific port, but did not specify
         # a certain source IP, will bind to the default loopback.
         source_ip_bind = '::1' if af == socket.AF_INET6 else '127.0.0.1'
         # Trying to use the same address family as the requested af socket:
         # - 127.0.0.1 for IPv4
         # - ::1 for IPv6
     socket_obj = socket.socket(af)
     set_close_exec(socket_obj.fileno())
     if source_port_bind or source_ip_bind:
         # If the user requires binding also to a specific IP/port.
         try:
             socket_obj.bind((source_ip_bind, source_port_bind))
         except socket.error:
             socket_obj.close()
             # Fail loudly if unable to use the IP/port.
             raise
     try:
         stream = IOStream(socket_obj,
                           max_buffer_size=max_buffer_size)
     except socket.error as e:
         fu = Future()
         fu.set_exception(e)
         return fu
     else:
         return stream, stream.connect(addr)
开发者ID:FlorianLudwig,项目名称:tornado,代码行数:34,代码来源:tcpclient.py

示例4: open

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
 def open(self):
     try:
         future = self._stream.open()
     except Exception as e:
         future = Future()
         future.set_exception(e)
     return future
开发者ID:snower,项目名称:TorThrift,代码行数:9,代码来源:transport.py

示例5: ManualCapClient

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [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

示例6: run

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
 def run(child_gr, *args, **kwargs):
     try:
         result = func(*args, **kwargs)
         if not is_future(result):
             return child_gr.switch(result)
     except Exception as e:
         result = Future()
         result.set_exception(e)
     return ioloop.add_future(result, child_gr.switch)
开发者ID:snower,项目名称:TorThrift,代码行数:11,代码来源:handler.py

示例7: side_effect

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
 def side_effect(request, **kwargs):
     if request is not HTTPRequest:
         request = HTTPRequest(request)
     buffer = StringIO(body)
     response = HTTPResponse(request, status_code, buffer=buffer)
     future = Future()
     if response.error:
         future.set_exception(response.error)
     else:
         future.set_result(response)
     return future
开发者ID:dmytro-laba,项目名称:cn,代码行数:13,代码来源:test_mixins.py

示例8: test_non_successful_responses_marks_client_as_failed

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
    def test_non_successful_responses_marks_client_as_failed(self):
        client = self.get_app().sentry_client
        with patch.object(client, "_failed_send") as mock_failed:
            with patch.object(client, "_send_remote") as mock_send:

                f = Future()
                f.set_exception(HTTPError(499, "error"))
                mock_send.return_value = f
                client.send()

                yield gen.sleep(0.01)  # we need to run after the async send
                assert mock_failed.called
开发者ID:getsentry,项目名称:raven-python,代码行数:14,代码来源:tests.py

示例9: _create_stream

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
 def _create_stream(self, max_buffer_size, af, addr):
     # Always connect in plaintext; we'll convert to ssl if necessary
     # after one connection has completed.
     try:
         stream = IOStream(socket.socket(af),
                         io_loop=self.io_loop,
                         max_buffer_size=max_buffer_size)
     except socket.error as e:
         fu = Future()
         fu.set_exception(e)
         return fu
     else:
         return stream.connect(addr)
开发者ID:homm,项目名称:tornado,代码行数:15,代码来源:tcpclient.py

示例10: _build_response

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
    def _build_response(self, tid):
        """
        Prepare for a response, returns a future
        :param tid:
        :return: Future
        """
        f = Future()

        if not self._connected:
            f.set_exception(ConnectionException("Client is not connected"))
            return f

        self.transaction.addTransaction(f, tid)
        return f
开发者ID:bashwork,项目名称:pymodbus,代码行数:16,代码来源:__init__.py

示例11: with_timeout

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
def with_timeout(timeout, future, io_loop=None):
    """Wraps a `.Future` in a timeout.

    Raises `TimeoutError` if the input future does not complete before
    ``timeout``, which may be specified in any form allowed by
    `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time
    relative to `.IOLoop.time`)

    Currently only supports Futures, not other `YieldPoint` classes.

    .. versionadded:: 4.0
    """
    # TODO: allow yield points in addition to futures?
    # Tricky to do with stack_context semantics.
    #
    # It's tempting to optimize this by cancelling the input future on timeout
    # instead of creating a new one, but A) we can't know if we are the only
    # one waiting on the input future, so cancelling it might disrupt other
    # callers and B) concurrent futures can only be cancelled while they are
    # in the queue, so cancellation cannot reliably bound our waiting time.
    result = Future()
    chain_future(future, result)
    if io_loop is None:
        io_loop = IOLoop.current()
    timeout_handle = io_loop.add_timeout(timeout, lambda: result.set_exception(TimeoutError("Timeout")))
    if isinstance(future, Future):
        # We know this future will resolve on the IOLoop, so we don't
        # need the extra thread-safety of IOLoop.add_future (and we also
        # don't care about StackContext here.
        future.add_done_callback(lambda future: io_loop.remove_timeout(timeout_handle))
    else:
        # concurrent.futures.Futures may resolve on any thread, so we
        # need to route them back to the IOLoop.
        io_loop.add_future(future, lambda future: io_loop.remove_timeout(timeout_handle))
    return result
开发者ID:BingQiangChen,项目名称:tornado,代码行数:37,代码来源:gen.py

示例12: test_fails_before_timeout

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
 def test_fails_before_timeout(self):
     future = Future()
     self.io_loop.add_timeout(
         datetime.timedelta(seconds=0.1),
         lambda: future.set_exception(ZeroDivisionError))
     with self.assertRaises(ZeroDivisionError):
         yield gen.with_timeout(datetime.timedelta(seconds=3600), future)
开发者ID:0xkag,项目名称:tornado,代码行数:9,代码来源:gen_test.py

示例13: test_unsuccessful_future

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
    def test_unsuccessful_future(self):
        class BadFuture(Exception):
            pass

        future = Future()

        def run():
            with self.assertRaises(BadFuture):
                utils.run_async(future)
            self.stop()

        gr = greenlet.greenlet(run)
        gr.switch()

        future.set_exception(BadFuture("you have been exterminated"))
        self.wait()
开发者ID:ef-ctx,项目名称:tornwamp,代码行数:18,代码来源:test_utils.py

示例14: open

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
    def open(self):
        if self._unix_socket:
            address = self._unix_socket
        else:
            address = (self._host, self._port)
        try:
            future = self.connect(address)
            if self._timeout > 0:
                def timeout():
                    if self._connecting:
                        self.close((None, TStreamConnectTimeoutError(), None))

                self.io_loop.add_timeout(time.time() + self._timeout, timeout)
        except Exception as e:
            future = Future()
            future.set_exception(e)
        return future
开发者ID:snower,项目名称:TorThrift,代码行数:19,代码来源:stream.py

示例15: GuarantedHTTPRequest

# 需要导入模块: from tornado.concurrent import Future [as 别名]
# 或者: from tornado.concurrent.Future import set_exception [as 别名]
class GuarantedHTTPRequest(HTTPRequest):
    def __init__(self, *args, **kwargs):
        self._first_chunk_recieved = False
        self.timeout_handle = None
        self._io_loop = ioloop.IOLoop.current()

        if "streaming_callback" in kwargs:
            self.orig_streaming_callback = kwargs["streaming_callback"]
        else:
            self.orig_streaming_callback = None

        if "inactive_timeout" in kwargs:
            self.inactive_timeout = kwargs["inactive_timeout"]
        else:
            self.inactive_timeout = 1
        del kwargs["inactive_timeout"]

        self.timeout_future = Future()
        kwargs["streaming_callback"] = self.stream_cb

        super(GuarantedHTTPRequest, self).__init__(*args, **kwargs)

    def stream_cb(self, data):
        self._first_chunk_recieved = True
        if self.orig_streaming_callback:
            self.orig_streaming_callback(data)
        io_loop = self._io_loop
        if self.timeout_handle:
            io_loop.remove_timeout(self.timeout_handle)
        self.timeout_handle = io_loop.call_at(io_loop.time()+1,
                                              self.throwStreamingTimeout)

    def throwStreamingTimeout(self):
        err = HTTPError(
            504,
            message="No activity from server for {} second(s)".format(
                self.inactive_timeout))
        self.timeout_future.set_exception(err)

    def done(self):
        if self._first_chunk_recieved:
            io_loop = self._io_loop
            io_loop.remove_timeout(self.timeout_handle)
开发者ID:yma-het,项目名称:tornado_smart_httpclient,代码行数:45,代码来源:SmartAsyncHttpClient.py


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