• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python concurrent.TracebackFuture类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: start_tls

    def start_tls(self, server_side, ssl_options, server_hostname=None):
        if not isinstance(ssl_options, SSL.Context):
            raise ValueError("ssl_options is not SSL.Context")

        _socket = self.detach()
        _socket = SSL.Connection(ssl_options, _socket)
        if server_side:
            _socket.set_accept_state()
        else:
            _socket.set_connect_state()
            if server_hostname:
                _socket.set_tlsext_host_name(server_hostname.encode("idna"))

        orig_close_callback = self._close_callback
        self._close_callback = None

        future = TracebackFuture()
        ssl_stream = MicroProxySSLIOStream(_socket,
                                           server_hostname=server_hostname,
                                           ssl_options=ssl_options,
                                           io_loop=self.io_loop)

        def close_callback():
            if not future.done():
                future.set_exception(ssl_stream.error or StreamClosedError())
            if orig_close_callback is not None:
                orig_close_callback()

        ssl_stream.set_close_callback(close_callback)
        ssl_stream._ssl_connect_callback = lambda: future.set_result(ssl_stream)
        ssl_stream.max_buffer_size = self.max_buffer_size
        ssl_stream.read_chunk_size = self.read_chunk_size
        return future
开发者ID:mike820324,项目名称:microProxy,代码行数:33,代码来源:iostream.py


示例2: _defer_to_future

 def _defer_to_future(defer):
     future = TracebackFuture()
     defer.addCallbacks(
         future.set_result,
         lambda failure: future.set_exc_info(
             (failure.type, failure.value, failure.tb)))
     return future
开发者ID:geerk,项目名称:toradbapi,代码行数:7,代码来源:toradbapi.py


示例3: StubWebSocketClientConnection

class StubWebSocketClientConnection(object):
    """A stub version of tornado.websocket.WebSocketClientConnection for use in
    unit tests.

    Attributes:
        TIMEOUT: class constant, which should be overridden in subclasses, in
            order to vary the time from when the class is instantiated until the
            returned future is resolved.
        connect_future: the Future resolved when the client "connection" is
            made.
        written_messages: a list of messages passed to the write_message
            method to see they have been received.
    """
    TIMEOUT = datetime.timedelta(milliseconds=0)

    def __init__(self, io_loop, request, on_message_callback=None,
                 compression_options=None):
        del request, on_message_callback, compression_options
        self.connect_future = TracebackFuture()
        self.written_messages = []

        io_loop.add_timeout(self.TIMEOUT, self._complete)

    def _complete(self):
        self.connect_future.set_result(self)

    def write_message(self, message):
        """Adds writen message to the written_messages buffer."""
        self.written_messages.append(message)
开发者ID:willjschmitt,项目名称:joulia-controller,代码行数:29,代码来源:stub_websocket.py


示例4: open

 def open(self):
     future = TracebackFuture()
     try:
         self._stream.open(lambda :future.set_result(None))
     except Exception:
         future.set_exc_info(sys.exc_info())
     return future
开发者ID:ethaniz,项目名称:TorThrift,代码行数:7,代码来源:transport.py


示例5: fetch

    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 = TracebackFuture()
        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(response)
        self.fetch_impl(request, handle_response)
        return future
开发者ID:mikolajb,项目名称:tornado,代码行数:56,代码来源:httpclient.py


示例6: close

 def close(self):
     if self._cursor is None:
         future = TracebackFuture()
         future.set_result(None)
         return future
     future = async_call_method(self._cursor.close)
     def do_close(future):
         self._cursor = None
     future.add_done_callback(do_close)
     return future
开发者ID:bluerover,项目名称:TorMySQL,代码行数:10,代码来源:cursor.py


示例7: register

 def register(self, name, callback=None):
     msg_id = next(self._generator)
     request = packer.dumps(('register', name))
     buff = struct.pack('!ibi', len(request), RPC_REGISTER, msg_id) + request
     future = TracebackFuture()
     if callback:
         future.add_done_callback(callback)
     self.add_request_table(msg_id, future)
     self.write(buff)
     return future
开发者ID:ethaniz,项目名称:torpc,代码行数:10,代码来源:rpc.py


示例8: fetch

    def fetch(self, url, headers=None, body=None, method="GET", callback=None, raise_error=True, cache=None, **kwargs):
        headers = headers or {}
        body = body or "{}"
        """very simlar with AsyncHTTPClient.fetch
        """
        if self._closed:
            raise RuntimeError("fetch() called on closed AsyncHTTPClient")
        future = TracebackFuture()
        if isinstance(body, dict):
            for k,v in body.items():
                if v is None:
                    del body[k]
            body = urllib.urlencode(body)
        for k,v in headers.items(): #headers 只能接收str
            if v:
                headers[k] = str(headers[k])
            else:
                del headers[k]
        request = HTTPRequest(url=url,method=method,headers=headers,body=body, allow_nonstandard_methods=True, request_timeout=600 ,**kwargs)
        # 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)
        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:
                try:
                    resp = json.loads(str(response.body))
                    if resp.get("statusCode") and resp.get("statusCode")==800:
                        future.set_result(resp)
                        log.info(json.dumps({"response":resp,"body":body,"headers":headers,"url":url}))
                    else:
                        future.set_result({"error_type":"statusCode is not 800", "response":resp,"body":body,"headers":headers,"url":url})
                        log.error(json.dumps({"error_type":"statusCode is not 800", "response":resp,"body":body,"headers":headers,"url":url}))
                except Exception,e:
                    future.set_result({"error_type":"json.loads failed!","error":str(e),"response.body":response.body,"body":body,"headers":headers,"url":url})
                    log.error(json.dumps({"error_type":"json.loads failed!","error":str(e),"response.body":response.body,"body":body,"headers":headers,"url":url}))
开发者ID:astwyg,项目名称:ct-fcore,代码行数:55,代码来源:client.py


示例9: handle_yield

    def handle_yield(self, yielded):
        # Lists containing YieldPoints require stack contexts;
        # other lists are handled via multi_future in convert_yielded.
        if (isinstance(yielded, list) and
                any(isinstance(f, YieldPoint) for f in yielded)):
            yielded = Multi(yielded)
        elif (isinstance(yielded, dict) and
              any(isinstance(f, YieldPoint) for f in yielded.values())):
            yielded = Multi(yielded)

        if isinstance(yielded, YieldPoint):
            # YieldPoints are too closely coupled to the Runner to go
            # through the generic convert_yielded mechanism.
            self.future = TracebackFuture()

            def start_yield_point():
                try:
                    yielded.start(self)
                    if yielded.is_ready():
                        self.future.set_result(
                            yielded.get_result())
                    else:
                        self.yield_point = yielded
                except Exception:
                    self.future = TracebackFuture()
                    self.future.set_exc_info(sys.exc_info())

            if self.stack_context_deactivate is None:
                # Start a stack context if this is the first
                # YieldPoint we've seen.
                with stack_context.ExceptionStackContext(
                        self.handle_exception) as deactivate:
                    self.stack_context_deactivate = deactivate

                    def cb():
                        start_yield_point()
                        self.run()
                    self.io_loop.add_callback(cb)
                    return False
            else:
                start_yield_point()
        else:
            try:
                self.future = convert_yielded(yielded)
            except BadYieldError:
                self.future = TracebackFuture()
                self.future.set_exc_info(sys.exc_info())

        if not self.future.done() or self.future is moment:
            self.io_loop.add_future(
                self.future, lambda f: self.run())
            return False
        return True
开发者ID:jampp,项目名称:tornado,代码行数:53,代码来源:gen.py


示例10: handle_yield

    def handle_yield(self, yielded):
        # Lists containing YieldPoints require stack contexts;
        # other lists are handled in convert_yielded.
        if _contains_yieldpoint(yielded):
            yielded = multi(yielded)

        if isinstance(yielded, YieldPoint):
            # YieldPoints are too closely coupled to the Runner to go
            # through the generic convert_yielded mechanism.
            self.future = TracebackFuture()

            def start_yield_point():
                try:
                    yielded.start(self)
                    if yielded.is_ready():
                        self.future.set_result(
                            yielded.get_result())
                    else:
                        self.yield_point = yielded
                except Exception:
                    self.future = TracebackFuture()
                    self.future.set_exc_info(sys.exc_info())

            if self.stack_context_deactivate is None:
                # Start a stack context if this is the first
                # YieldPoint we've seen.
                with stack_context.ExceptionStackContext(
                        self.handle_exception) as deactivate:
                    self.stack_context_deactivate = deactivate

                    def cb():
                        start_yield_point()
                        self.run()
                    self.io_loop.add_callback(cb)
                    return False
            else:
                start_yield_point()
        else:
            try:
                self.future = convert_yielded(yielded)
            except BadYieldError:
                self.future = TracebackFuture()
                self.future.set_exc_info(sys.exc_info())

        if not self.future.done() or self.future is moment:
            def inner(f):
                # Break a reference cycle to speed GC.
                f = None # noqa
                self.run()
            self.io_loop.add_future(
                self.future, inner)
            return False
        return True
开发者ID:FlorianLudwig,项目名称:tornado,代码行数:53,代码来源:gen.py


示例11: call

    def call(self, method_name, *arg, **kwargs):
        _callback = kwargs.get('callback')
        msg_id = next(self._generator)
        request = packer.dumps((method_name, arg))
        buff = struct.pack('!ibi', len(request), RPC_REQUEST, msg_id) + request

        future = TracebackFuture()
        self.add_request_table(msg_id, future)

        if _callback:
            future.add_done_callback(_callback)
        self.write(buff)
        return future
开发者ID:ethaniz,项目名称:torpc,代码行数:13,代码来源:rpc.py


示例12: fetch

    def fetch(self, request, callback=None, **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`.  The ``Future`` wil raise an `HTTPError` if
        the request returned a non-200 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 not isinstance(request, HTTPRequest):
            request = HTTPRequest(url=request, **kwargs)
        # 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)
        if options.client_trace:
            request.trace.record(Annotation.client_send())
        request = _RequestProxy(request, self.defaults)
        future = TracebackFuture()
        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 response.error:
                future.set_exception(response.error)
            else:
                future.set_result(response)
            if options.client_trace:
                request.trace.record(Annotation.client_recv())
        self.fetch_impl(request, handle_response)
        return future
开发者ID:iambocai,项目名称:tornado,代码行数:51,代码来源:httpclient.py


示例13: mock_fetch

    def mock_fetch(self, request, callback=None, **kwargs):
        future = TracebackFuture()
        if callback is not None:
            callback = stack_context.wrap(callback)

            def handle_future(future):
                response = future.result()
                self.io_loop.add_callback(callback, response)
            future.add_done_callback(handle_future)

        res = MagicMock()
        future.set_result(res)

        return future
开发者ID:MyGGaN,项目名称:mixpanel-python,代码行数:14,代码来源:test_async.py


示例14: fetch

 def fetch(self, request, callback=None, **kwargs):
     if not isinstance(request, HTTPRequest):
         request = HTTPRequest(url=request, **kwargs)
     response_partial = RequestCollection.find(request)
     if response_partial:
         resp = response_partial(request)
     else:
         resp = HTTPResponse(request, 404)
     if callback is not None:
         callback(resp)
     else:
         future = TracebackFuture()
         future.set_result(resp)
         return future
开发者ID:acmiracl,项目名称:maas-sdk-tornado,代码行数:14,代码来源:test_miracl_api_tornado.py


示例15: handle_yield

    def handle_yield(self, yielded):
        if isinstance(yielded, list):
            if all(is_future(f) for f in yielded):
                yielded = multi_future(yielded)
            else:
                yielded = Multi(yielded)
        elif isinstance(yielded, dict):
            if all(is_future(f) for f in yielded.values()):
                yielded = multi_future(yielded)
            else:
                yielded = Multi(yielded)

        if isinstance(yielded, YieldPoint):
            self.future = TracebackFuture()
            def start_yield_point():
                try:
                    yielded.start(self)
                    if yielded.is_ready():
                        self.future.set_result(
                            yielded.get_result())
                    else:
                        self.yield_point = yielded
                except Exception:
                    self.future = TracebackFuture()
                    self.future.set_exc_info(sys.exc_info())
            if self.stack_context_deactivate is None:
                # Start a stack context if this is the first
                # YieldPoint we've seen.
                with stack_context.ExceptionStackContext(
                        self.handle_exception) as deactivate:
                    self.stack_context_deactivate = deactivate
                    def cb():
                        start_yield_point()
                        self.run()
                    self.io_loop.add_callback(cb)
                    return False
            else:
                start_yield_point()
        elif is_future(yielded):
            self.future = yielded
            if not self.future.done() or self.future is moment:
                self.io_loop.add_future(
                    self.future, lambda f: self.run())
                return False
        else:
            self.future = TracebackFuture()
            self.future.set_exception(BadYieldError(
                "yielded unknown object %r" % (yielded,)))
        return True
开发者ID:6api,项目名称:luokr.com,代码行数:49,代码来源:gen.py


示例16: wrapper

 def wrapper(*args, **kwargs):
     future = TracebackFuture()
     callback, args, kwargs = replacer.replace(future, args, kwargs)
     if callback is not None:
         future.add_done_callback(
             functools.partial(_auth_future_to_callback, callback))
     def handle_exception(typ, value, tb):
         if future.done():
             return False
         else:
             future.set_exc_info((typ, value, tb))
             return True
     with ExceptionStackContext(handle_exception):
         f(*args, **kwargs)
     return future
开发者ID:marslabtron,项目名称:durotar,代码行数:15,代码来源:auth.py


示例17: __init__

    def __init__(self, io_loop, request, on_message_callback=None,
                 compression_options=None):
        del request, on_message_callback, compression_options
        self.connect_future = TracebackFuture()
        self.written_messages = []

        io_loop.add_timeout(self.TIMEOUT, self._complete)
开发者ID:willjschmitt,项目名称:joulia-controller,代码行数:7,代码来源:stub_websocket.py


示例18: __init__

    def __init__(self, io_loop, request, compression_options=None):
        self.compression_options = compression_options
        self.connect_future = TracebackFuture()
        self.read_future = None
        self.read_queue = collections.deque()
        self.key = base64.b64encode(os.urandom(16))

        scheme, sep, rest = request.url.partition(":")
        scheme = {"ws": "http", "wss": "https"}[scheme]
        request.url = scheme + sep + rest
        request.headers.update(
            {
                "Upgrade": "websocket",
                "Connection": "Upgrade",
                "Sec-WebSocket-Key": self.key,
                "Sec-WebSocket-Version": "13",
            }
        )
        if self.compression_options is not None:
            # Always offer to let the server set our max_wbits (and even though
            # we don't offer it, we will accept a client_no_context_takeover
            # from the server).
            # TODO: set server parameters for deflate extension
            # if requested in self.compression_options.
            request.headers["Sec-WebSocket-Extensions"] = "permessage-deflate; client_max_window_bits"

        self.tcp_client = TCPClient(io_loop=io_loop)
        super(WebSocketClientConnection, self).__init__(
            io_loop, None, request, lambda: None, self._on_http_response, 104857600, self.tcp_client, 65536
        )
开发者ID:sabermonk,项目名称:tornado,代码行数:30,代码来源:websocket.py


示例19: __init__

 def __init__(self, future=None):
     if future is not None:
         self._future = future
     else:
         self._future = TracebackFuture()
         self._future.add_done_callback(functools.partial(async_result_complete, self))
     self._condition = threading.Condition()
开发者ID:tristeng,项目名称:kazoo,代码行数:7,代码来源:tornado.py


示例20: __init__

    def __init__(self, io_loop, request, on_message_callback=None,
                 compression_options=None):
        self.compression_options = compression_options
        self.connect_future = TracebackFuture()
        self.protocol = None
        self.read_future = None
        self.read_queue = collections.deque()
        self.key = base64.b64encode(os.urandom(16))
        self._on_message_callback = on_message_callback
        self.close_code = self.close_reason = None

        scheme, sep, rest = request.url.partition(':')
        scheme = {'ws': 'http', 'wss': 'https'}[scheme]
        request.url = scheme + sep + rest
        request.headers.update({
            'Upgrade': 'websocket',
            'Connection': 'Upgrade',
            'Sec-WebSocket-Key': self.key,
            'Sec-WebSocket-Version': '13',
        })
        if self.compression_options is not None:
            # Always offer to let the server set our max_wbits (and even though
            # we don't offer it, we will accept a client_no_context_takeover
            # from the server).
            # TODO: set server parameters for deflate extension
            # if requested in self.compression_options.
            request.headers['Sec-WebSocket-Extensions'] = (
                'permessage-deflate; client_max_window_bits')

        self.tcp_client = TCPClient(io_loop=io_loop)
        super(WebSocketClientConnection, self).__init__(
            io_loop, None, request, lambda: None, self._on_http_response,
            104857600, self.tcp_client, 65536, 104857600)
开发者ID:437049211,项目名称:PyQYT,代码行数:33,代码来源:websocket.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python curl_httpclient.CurlAsyncHTTPClient类代码示例发布时间:2022-05-27
下一篇:
Python concurrent.Future类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap