defer.py 文件源码

python
阅读 31 收藏 0 点赞 0 评论 0

项目:zenchmarks 作者: squeaky-pl 项目源码 文件源码
def ensureDeferred(coro):
    """
    Schedule the execution of a coroutine that awaits/yields from L{Deferred}s,
    wrapping it in a L{Deferred} that will fire on success/failure of the
    coroutine. If a Deferred is passed to this function, it will be returned
    directly (mimicing C{asyncio}'s C{ensure_future} function).

    Coroutine functions return a coroutine object, similar to how generators
    work. This function turns that coroutine into a Deferred, meaning that it
    can be used in regular Twisted code. For example::

        import treq
        from twisted.internet.defer import ensureDeferred
        from twisted.internet.task import react

        async def crawl(pages):
            results = {}
            for page in pages:
                results[page] = await treq.content(await treq.get(page))
            return results

        def main(reactor):
            pages = [
                "http://localhost:8080"
            ]
            d = ensureDeferred(crawl(pages))
            d.addCallback(print)
            return d

        react(main)

    @param coro: The coroutine object to schedule, or a L{Deferred}.
    @type coro: A Python 3.5+ C{async def} C{coroutine}, a Python 3.3+
        C{yield from} using L{types.GeneratorType}, or a L{Deferred}.

    @rtype: L{Deferred}
    """
    from types import GeneratorType

    if version_info >= (3, 4, 0):
        from asyncio import iscoroutine

        if iscoroutine(coro) or isinstance(coro, GeneratorType):
            return _inlineCallbacks(None, coro, Deferred())

    elif version_info >= (3, 3, 0):
        if isinstance(coro, GeneratorType):
            return _inlineCallbacks(None, coro, Deferred())

    if not isinstance(coro, Deferred):
        raise ValueError("%r is not a coroutine or a Deferred" % (coro,))

    # Must be a Deferred
    return coro
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号