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


Python defer.ensureDeferred方法代码示例

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


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

示例1: setUp

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import ensureDeferred [as 别名]
def setUp(self):
        reactor = ExtendedMemoryReactorClock()

        config = {"apps": {}, "log": {"setup": {"version": 1}}}

        self.config_setup(config)

        config = merge_left_with_defaults(CONFIG_DEFAULTS, config)
        if USE_POSTGRES:
            self._set_up_database(self.dbname)

        self.sygnal = Sygnal(config, reactor)
        self.sygnal.database.start()
        self.v1api = PushGatewayApiServer(self.sygnal)

        start_deferred = ensureDeferred(
            self.sygnal._make_pushkins_then_start(0, [], None)
        )

        while not start_deferred.called:
            # we need to advance until the pushkins have started up
            self.sygnal.reactor.advance(1)
            self.sygnal.reactor.wait_for_work(lambda: start_deferred.called) 
开发者ID:matrix-org,项目名称:sygnal,代码行数:25,代码来源:testutils.py

示例2: test_passesThroughDeferreds

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import ensureDeferred [as 别名]
def test_passesThroughDeferreds(self):
        """
        L{defer.ensureDeferred} will pass through a Deferred unchanged.
        """
        d = defer.Deferred()
        d2 = defer.ensureDeferred(d)
        self.assertIs(d, d2) 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:9,代码来源:test_defer.py

示例3: test_willNotAllowNonDeferredOrCoroutine

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import ensureDeferred [as 别名]
def test_willNotAllowNonDeferredOrCoroutine(self):
        """
        Passing L{defer.ensureDeferred} a non-coroutine and a non-Deferred will
        raise a L{ValueError}.
        """
        with self.assertRaises(ValueError):
            defer.ensureDeferred("something") 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:9,代码来源:test_defer.py

示例4: as_future

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import ensureDeferred [as 别名]
def as_future(self, fun, *args, **kwargs):
        # Twisted doesn't automagically deal with coroutines on Py3
        if iscoroutinefunction(fun):
            return ensureDeferred(fun(*args, **kwargs))
        return maybeDeferred(fun, *args, **kwargs) 
开发者ID:crossbario,项目名称:txaio,代码行数:7,代码来源:tx.py

示例5: defer

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import ensureDeferred [as 别名]
def defer(coroutine: typing.Union[typing.Coroutine, asyncio.Future]):
    """
    Create a twisted Deferred from a coroutine or future and ensure it will run (call ensureDeferred on it).
    :param coroutine: coroutine to defer.
    """
    from twisted.internet.defer import ensureDeferred, Deferred

    ensureDeferred(Deferred.fromFuture(asyncio.ensure_future(coroutine))) 
开发者ID:GoSecure,项目名称:pyrdp,代码行数:10,代码来源:defer.py

示例6: run

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import ensureDeferred [as 别名]
def run(self):
        """
        Attempt to run Sygnal and then exit the application.
        """
        port = int(self.config["http"]["port"])
        bind_addresses = self.config["http"]["bind_addresses"]
        pushgateway_api = PushGatewayApiServer(self)

        @defer.inlineCallbacks
        def start():
            try:
                yield ensureDeferred(
                    self._make_pushkins_then_start(
                        port, bind_addresses, pushgateway_api
                    )
                )
            except Exception:
                # Print the exception and bail out.
                print("Error during startup:", file=sys.stderr)

                # this gives better tracebacks than traceback.print_exc()
                Failure().printTraceback(file=sys.stderr)

                if self.reactor.running:
                    self.reactor.stop()

        self.reactor.callWhenRunning(start)
        self.reactor.run() 
开发者ID:matrix-org,项目名称:sygnal,代码行数:30,代码来源:sygnal.py

示例7: advance_rotation

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import ensureDeferred [as 别名]
def advance_rotation(self, message: Optional[str] = None) -> Deferred:
        """
        Advances to the next map in the rotation. If message is provided
        it will send it to the chat, waits for 10 seconds and then advances.

        Returns:
            Deferred that fires when the map has been loaded
        """
        self.set_time_limit(False)
        if self.planned_map is None:
            self.planned_map = next(self.map_rotator)
        planned_map = self.planned_map
        self.planned_map = None
        self.on_advance(planned_map)

        async def do_advance():
            if message is not None:
                log.info("advancing to map '{name}' ({reason}) in 10 seconds",
                         name=planned_map.full_name, reason=message)
                self.broadcast_chat(
                    '{} Next map: {}.'.format(message, planned_map.full_name),
                    irc=True)
                await sleep(10)
            else:
                log.info("advancing to map '{name}'",
                         name=planned_map.full_name)

            await self.set_map_name(planned_map)

        return ensureDeferred(do_advance()) 
开发者ID:piqueserver,项目名称:piqueserver,代码行数:32,代码来源:server.py

示例8: test_run

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import ensureDeferred [as 别名]
def test_run(self):

        args = Namespace()
        args.command = "on"
        args.driver = "fake"

        driver = FakeDriver()
        registry = {"fake": driver}

        status = yield ensureDeferred(
            power_driver_command._run(reactor, args, registry)
        )
        self.assertEqual("on", status) 
开发者ID:maas,项目名称:maas,代码行数:15,代码来源:test_power_driver_command.py

示例9: run

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import ensureDeferred [as 别名]
def run(argv=None):

    if argv is None:
        argv = sys.argv[1:]

    args = _parse_args(argv)

    react(
        lambda *args, **kwargs: ensureDeferred(_run(*args, **kwargs)), [args]
    ) 
开发者ID:maas,项目名称:maas,代码行数:12,代码来源:power_driver_command.py

示例10: run

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import ensureDeferred [as 别名]
def run(reactor, cfg, tor, if_unused, verbose, list, build, delete):
    if list:
        await list_circuits(reactor, cfg, tor, verbose)

    elif len(delete) > 0:
        deletes = []
        for d in delete:
            deletes.append(delete_circuit(reactor, cfg, tor, d, if_unused))
        results = await defer.DeferredList([defer.ensureDeferred(d) for d in deletes])
        for ok, value in results:
            if not ok:
                raise value

    elif build:
        await build_circuit(reactor, cfg, tor, build.split(',')) 
开发者ID:meejah,项目名称:carml,代码行数:17,代码来源:carml_circ.py

示例11: lineReceived

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import ensureDeferred [as 别名]
def lineReceived(self, line):
        # Ignore blank lines
        if not line:
            return
        keys = line.split()
        # we really do want this to be a Deferred because lineReceived
        # isn't (can't be) an async method..
        token = object()
        self.outstanding.append(token)
        d = defer.ensureDeferred(do_cmd(self.proto, tuple(keys)))
        d.addCallback(self._completed, token)
        d.addErrback(self._error, token) 
开发者ID:meejah,项目名称:carml,代码行数:14,代码来源:carml_cmd.py

示例12: ensureDeferred

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import ensureDeferred [as 别名]
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 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:56,代码来源:defer.py

示例13: ensureDeferred

# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import ensureDeferred [as 别名]
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.4+
        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 _cancellableInlineCallbacks(coro)

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

    # Must be a Deferred
    return coro 
开发者ID:wistbean,项目名称:learn_python3_spider,代码行数:52,代码来源:defer.py


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