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

Python concurrent.future_set_result_unless_cancelled函数代码示例

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

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



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

示例1: _on_twitter_request

 def _on_twitter_request(self, future, response):
     if response.error:
         future.set_exception(AuthError(
             "Error response %s fetching %s" % (response.error,
                                                response.request.url)))
         return
     future_set_result_unless_cancelled(future, escape.json_decode(response.body))
开发者ID:alexdxy,项目名称:tornado,代码行数:7,代码来源:auth.py


示例2: _on_authentication_verified

    def _on_authentication_verified(self, future, response):
        if response.error or b"is_valid:true" not in response.body:
            future.set_exception(AuthError(
                "Invalid OpenID response: %s" % (response.error or
                                                 response.body)))
            return

        # Make sure we got back at least an email from attribute exchange
        ax_ns = None
        for name in self.request.arguments:
            if name.startswith("openid.ns.") and \
                    self.get_argument(name) == u"http://openid.net/srv/ax/1.0":
                ax_ns = name[10:]
                break

        def get_ax_arg(uri):
            if not ax_ns:
                return u""
            prefix = "openid." + ax_ns + ".type."
            ax_name = None
            for name in self.request.arguments.keys():
                if self.get_argument(name) == uri and name.startswith(prefix):
                    part = name[len(prefix):]
                    ax_name = "openid." + ax_ns + ".value." + part
                    break
            if not ax_name:
                return u""
            return self.get_argument(ax_name, u"")

        email = get_ax_arg("http://axschema.org/contact/email")
        name = get_ax_arg("http://axschema.org/namePerson")
        first_name = get_ax_arg("http://axschema.org/namePerson/first")
        last_name = get_ax_arg("http://axschema.org/namePerson/last")
        username = get_ax_arg("http://axschema.org/namePerson/friendly")
        locale = get_ax_arg("http://axschema.org/pref/language").lower()
        user = dict()
        name_parts = []
        if first_name:
            user["first_name"] = first_name
            name_parts.append(first_name)
        if last_name:
            user["last_name"] = last_name
            name_parts.append(last_name)
        if name:
            user["name"] = name
        elif name_parts:
            user["name"] = u" ".join(name_parts)
        elif email:
            user["name"] = email.split("@")[0]
        if email:
            user["email"] = email
        if locale:
            user["locale"] = locale
        if username:
            user["username"] = username
        claimed_id = self.get_argument("openid.claimed_id", None)
        if claimed_id:
            user["claimed_id"] = claimed_id
        future_set_result_unless_cancelled(future, user)
开发者ID:alexdxy,项目名称:tornado,代码行数:59,代码来源:auth.py


示例3: _on_oauth2_request

    def _on_oauth2_request(self, future, response_fut):
        try:
            response = response_fut.result()
        except Exception as e:
            future.set_exception(AuthError("Error response %s" % e))
            return

        future_set_result_unless_cancelled(future, escape.json_decode(response.body))
开发者ID:JackDandy,项目名称:SickGear,代码行数:8,代码来源:auth.py


示例4: _on_access_token

    def _on_access_token(self, future, response):
        """Callback function for the exchange to the access token."""
        if response.error:
            future.set_exception(AuthError('Google auth error: %s' % str(response)))
            return

        args = escape.json_decode(response.body)
        future_set_result_unless_cancelled(future, args)
开发者ID:alexdxy,项目名称:tornado,代码行数:8,代码来源:auth.py


示例5: _on_twitter_request

 def _on_twitter_request(self, future, url, response_fut):
     try:
         response = response_fut.result()
     except Exception as e:
         future.set_exception(AuthError(
             "Error response %s fetching %s" % (e, url)))
         return
     future_set_result_unless_cancelled(future, escape.json_decode(response.body))
开发者ID:JackDandy,项目名称:SickGear,代码行数:8,代码来源:auth.py


示例6: callback

 def callback(ret: int) -> None:
     if ret != 0 and raise_error:
         # Unfortunately we don't have the original args any more.
         future_set_exception_unless_cancelled(
             future, CalledProcessError(ret, "unknown")
         )
     else:
         future_set_result_unless_cancelled(future, ret)
开发者ID:bdarnell,项目名称:tornado,代码行数:8,代码来源:process.py


示例7: on_message

 def on_message(self, message):
     if self._on_message_callback:
         self._on_message_callback(message)
     elif self.read_future is not None:
         future_set_result_unless_cancelled(self.read_future, message)
         self.read_future = None
     else:
         self.read_queue.append(message)
开发者ID:alexdxy,项目名称:tornado,代码行数:8,代码来源:websocket.py


示例8: wrapper

 def wrapper(*args, **kwargs):
     # type: (*Any, **Any) -> Future[_T]
     # This function is type-annotated with a comment to work around
     # https://bitbucket.org/pypy/pypy/issues/2868/segfault-with-args-type-annotation-in
     future = _create_future()
     try:
         result = func(*args, **kwargs)
     except (Return, StopIteration) as e:
         result = _value_from_stopiteration(e)
     except Exception:
         future_set_exc_info(future, sys.exc_info())
         try:
             return future
         finally:
             # Avoid circular references
             future = None  # type: ignore
     else:
         if isinstance(result, Generator):
             # Inline the first iteration of Runner.run.  This lets us
             # avoid the cost of creating a Runner when the coroutine
             # never actually yields, which in turn allows us to
             # use "optional" coroutines in critical path code without
             # performance penalty for the synchronous case.
             try:
                 yielded = next(result)
             except (StopIteration, Return) as e:
                 future_set_result_unless_cancelled(
                     future, _value_from_stopiteration(e)
                 )
             except Exception:
                 future_set_exc_info(future, sys.exc_info())
             else:
                 # Provide strong references to Runner objects as long
                 # as their result future objects also have strong
                 # references (typically from the parent coroutine's
                 # Runner). This keeps the coroutine's Runner alive.
                 # We do this by exploiting the public API
                 # add_done_callback() instead of putting a private
                 # attribute on the Future.
                 # (Github issues #1769, #2229).
                 runner = Runner(result, future, yielded)
                 future.add_done_callback(lambda _: runner)
             yielded = None
             try:
                 return future
             finally:
                 # Subtle memory optimization: if next() raised an exception,
                 # the future's exc_info contains a traceback which
                 # includes this stack frame.  This creates a cycle,
                 # which will be collected at the next full GC but has
                 # been shown to greatly increase memory usage of
                 # benchmarks (relative to the refcount-based scheme
                 # used in the absence of cycles).  We can avoid the
                 # cycle by clearing the local variable after we return it.
                 future = None  # type: ignore
     future_set_result_unless_cancelled(future, result)
     return future
开发者ID:rgbkrk,项目名称:tornado,代码行数:57,代码来源:gen.py


示例9: multi_future

def multi_future(children, quiet_exceptions=()):
    """Wait for multiple asynchronous futures in parallel.

    This function is similar to `multi`, but does not support
    `YieldPoints <YieldPoint>`.

    .. versionadded:: 4.0

    .. versionchanged:: 4.2
       If multiple ``Futures`` fail, any exceptions after the first (which is
       raised) will be logged. Added the ``quiet_exceptions``
       argument to suppress this logging for selected exception types.

    .. deprecated:: 4.3
       Use `multi` instead.
    """
    if isinstance(children, dict):
        keys = list(children.keys())
        children = children.values()
    else:
        keys = None
    children = list(map(convert_yielded, children))
    assert all(is_future(i) for i in children)
    unfinished_children = set(children)

    future = _create_future()
    if not children:
        future_set_result_unless_cancelled(future,
                                           {} if keys is not None else [])

    def callback(f):
        unfinished_children.remove(f)
        if not unfinished_children:
            result_list = []
            for f in children:
                try:
                    result_list.append(f.result())
                except Exception as e:
                    if future.done():
                        if not isinstance(e, quiet_exceptions):
                            app_log.error("Multiple exceptions in yield list",
                                          exc_info=True)
                    else:
                        future_set_exc_info(future, sys.exc_info())
            if not future.done():
                if keys is not None:
                    future_set_result_unless_cancelled(future,
                                                       dict(zip(keys, result_list)))
                else:
                    future_set_result_unless_cancelled(future, result_list)

    listening = set()
    for f in children:
        if f not in listening:
            listening.add(f)
            future_add_done_callback(f, callback)
    return future
开发者ID:alexdxy,项目名称:tornado,代码行数:57,代码来源:gen.py


示例10: wrapper

    def wrapper(*args, **kwargs):
        future = _create_future()

        if replace_callback and 'callback' in kwargs:
            callback = kwargs.pop('callback')
            IOLoop.current().add_future(
                future, lambda future: callback(future.result()))

        try:
            result = func(*args, **kwargs)
        except (Return, StopIteration) as e:
            result = _value_from_stopiteration(e)
        except Exception:
            future_set_exc_info(future, sys.exc_info())
            try:
                return future
            finally:
                # Avoid circular references
                future = None
        else:
            if isinstance(result, GeneratorType):
                # Inline the first iteration of Runner.run.  This lets us
                # avoid the cost of creating a Runner when the coroutine
                # never actually yields, which in turn allows us to
                # use "optional" coroutines in critical path code without
                # performance penalty for the synchronous case.
                try:
                    orig_stack_contexts = stack_context._state.contexts
                    yielded = next(result)
                    if stack_context._state.contexts is not orig_stack_contexts:
                        yielded = _create_future()
                        yielded.set_exception(
                            stack_context.StackContextInconsistentError(
                                'stack_context inconsistency (probably caused '
                                'by yield within a "with StackContext" block)'))
                except (StopIteration, Return) as e:
                    future_set_result_unless_cancelled(future, _value_from_stopiteration(e))
                except Exception:
                    future_set_exc_info(future, sys.exc_info())
                else:
                    _futures_to_runners[future] = Runner(result, future, yielded)
                yielded = None
                try:
                    return future
                finally:
                    # Subtle memory optimization: if next() raised an exception,
                    # the future's exc_info contains a traceback which
                    # includes this stack frame.  This creates a cycle,
                    # which will be collected at the next full GC but has
                    # been shown to greatly increase memory usage of
                    # benchmarks (relative to the refcount-based scheme
                    # used in the absence of cycles).  We can avoid the
                    # cycle by clearing the local variable after we return it.
                    future = None
        future_set_result_unless_cancelled(future, result)
        return future
开发者ID:alexdxy,项目名称:tornado,代码行数:56,代码来源:gen.py


示例11: start_yield_point

 def start_yield_point():
     try:
         yielded.start(self)
         if yielded.is_ready():
             future_set_result_unless_cancelled(self.future, yielded.get_result())
         else:
             self.yield_point = yielded
     except Exception:
         self.future = Future()
         future_set_exc_info(self.future, sys.exc_info())
开发者ID:alexdxy,项目名称:tornado,代码行数:10,代码来源:gen.py


示例12: _on_oauth_get_user

 def _on_oauth_get_user(self, access_token, future, user_future):
     if user_future.exception() is not None:
         future.set_exception(user_future.exception())
         return
     user = user_future.result()
     if not user:
         future.set_exception(AuthError("Error getting user"))
         return
     user["access_token"] = access_token
     future_set_result_unless_cancelled(future, user)
开发者ID:JackDandy,项目名称:SickGear,代码行数:10,代码来源:auth.py


示例13: handle_response

 def handle_response(response):
     if raise_error and response.error:
         if isinstance(response.error, HTTPError):
             response.error.response = response
         future.set_exception(response.error)
     else:
         if response.error and not response._error_is_response_code:
             warnings.warn("raise_error=False will allow '%s' to be raised in the future" %
                           response.error, DeprecationWarning)
         future_set_result_unless_cancelled(future, response)
开发者ID:dkdenza,项目名称:tornado,代码行数:10,代码来源:httpclient.py


示例14: _finish_request

 def _finish_request(self, future):
     self._clear_callbacks()
     if not self.is_client and self._disconnect_on_finish:
         self.close()
         return
     # Turn Nagle's algorithm back on, leaving the stream in its
     # default state for the next request.
     self.stream.set_nodelay(False)
     if not self._finish_future.done():
         future_set_result_unless_cancelled(self._finish_future, None)
开发者ID:eomsoft,项目名称:teleport,代码行数:10,代码来源:http1connection.py


示例15: _on_connection_close

 def _on_connection_close(self):
     # Note that this callback is only registered on the IOStream
     # when we have finished reading the request and are waiting for
     # the application to produce its response.
     if self._close_callback is not None:
         callback = self._close_callback
         self._close_callback = None
         callback()
     if not self._finish_future.done():
         future_set_result_unless_cancelled(self._finish_future, None)
     self._clear_callbacks()
开发者ID:eomsoft,项目名称:teleport,代码行数:11,代码来源:http1connection.py


示例16: set_result

 def set_result(self, key, result):
     """Sets the result for ``key`` and attempts to resume the generator."""
     self.results[key] = result
     if self.yield_point is not None and self.yield_point.is_ready():
         try:
             future_set_result_unless_cancelled(self.future,
                                                self.yield_point.get_result())
         except:
             future_set_exc_info(self.future, sys.exc_info())
         self.yield_point = None
         self.run()
开发者ID:alexdxy,项目名称:tornado,代码行数:11,代码来源:gen.py


示例17: notify

    def notify(self, n: int = 1) -> None:
        """Wake ``n`` waiters."""
        waiters = []  # Waiters we plan to run right now.
        while n and self._waiters:
            waiter = self._waiters.popleft()
            if not waiter.done():  # Might have timed out.
                n -= 1
                waiters.append(waiter)

        for waiter in waiters:
            future_set_result_unless_cancelled(waiter, True)
开发者ID:rgbkrk,项目名称:tornado,代码行数:11,代码来源:locks.py


示例18: run

    def run(self) -> None:
        """Starts or resumes the generator, running until it reaches a
        yield point that is not ready.
        """
        if self.running or self.finished:
            return
        try:
            self.running = True
            while True:
                future = self.future
                if future is None:
                    raise Exception("No pending future")
                if not future.done():
                    return
                self.future = None
                try:
                    exc_info = None

                    try:
                        value = future.result()
                    except Exception:
                        exc_info = sys.exc_info()
                    future = None

                    if exc_info is not None:
                        try:
                            yielded = self.gen.throw(*exc_info)  # type: ignore
                        finally:
                            # Break up a reference to itself
                            # for faster GC on CPython.
                            exc_info = None
                    else:
                        yielded = self.gen.send(value)

                except (StopIteration, Return) as e:
                    self.finished = True
                    self.future = _null_future
                    future_set_result_unless_cancelled(
                        self.result_future, _value_from_stopiteration(e)
                    )
                    self.result_future = None  # type: ignore
                    return
                except Exception:
                    self.finished = True
                    self.future = _null_future
                    future_set_exc_info(self.result_future, sys.exc_info())
                    self.result_future = None  # type: ignore
                    return
                if not self.handle_yield(yielded):
                    return
                yielded = None
        finally:
            self.running = False
开发者ID:rgbkrk,项目名称:tornado,代码行数:53,代码来源:gen.py


示例19: _on_write_complete

 def _on_write_complete(self, future):
     exc = future.exception()
     if exc is not None and not isinstance(exc, iostream.StreamClosedError):
         future.result()
     if self._write_callback is not None:
         callback = self._write_callback
         self._write_callback = None
         self.stream.io_loop.add_callback(callback)
     if self._write_future is not None:
         future = self._write_future
         self._write_future = None
         future_set_result_unless_cancelled(future, None)
开发者ID:eomsoft,项目名称:teleport,代码行数:12,代码来源:http1connection.py


示例20: test_future_set_result_unless_cancelled

    def test_future_set_result_unless_cancelled(self):
        fut = Future()
        future_set_result_unless_cancelled(fut, 42)
        self.assertEqual(fut.result(), 42)
        self.assertFalse(fut.cancelled())

        fut = Future()
        fut.cancel()
        is_cancelled = fut.cancelled()
        future_set_result_unless_cancelled(fut, 42)
        self.assertEqual(fut.cancelled(), is_cancelled)
        if not is_cancelled:
            self.assertEqual(fut.result(), 42)
开发者ID:alexdxy,项目名称:tornado,代码行数:13,代码来源:concurrent_test.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python concurrent.is_future函数代码示例发布时间:2022-05-27
下一篇:
Python concurrent.chain_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