Python twisted.internet.defer.ensureDeferred() Examples

The following are 15 code examples of twisted.internet.defer.ensureDeferred(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.internet.defer , or try the search function .
Example #1
Source File: testutils.py    From sygnal with Apache License 2.0 6 votes vote down vote up
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) 
Example #2
Source File: test_defer.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_passesThroughDeferreds(self):
        """
        L{defer.ensureDeferred} will pass through a Deferred unchanged.
        """
        d = defer.Deferred()
        d2 = defer.ensureDeferred(d)
        self.assertIs(d, d2) 
Example #3
Source File: test_defer.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
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") 
Example #4
Source File: tx.py    From txaio with MIT License 5 votes vote down vote up
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) 
Example #5
Source File: test_defer.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_passesThroughDeferreds(self):
        """
        L{defer.ensureDeferred} will pass through a Deferred unchanged.
        """
        d = defer.Deferred()
        d2 = defer.ensureDeferred(d)
        self.assertIs(d, d2) 
Example #6
Source File: test_defer.py    From learn_python3_spider with MIT License 5 votes vote down vote up
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") 
Example #7
Source File: defer.py    From pyrdp with GNU General Public License v3.0 5 votes vote down vote up
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))) 
Example #8
Source File: sygnal.py    From sygnal with Apache License 2.0 5 votes vote down vote up
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() 
Example #9
Source File: server.py    From piqueserver with GNU General Public License v3.0 5 votes vote down vote up
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()) 
Example #10
Source File: test_power_driver_command.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
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) 
Example #11
Source File: power_driver_command.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
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]
    ) 
Example #12
Source File: carml_circ.py    From carml with The Unlicense 5 votes vote down vote up
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(',')) 
Example #13
Source File: carml_cmd.py    From carml with The Unlicense 5 votes vote down vote up
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) 
Example #14
Source File: defer.py    From Safejumper-for-Desktop with GNU General Public License v2.0 4 votes vote down vote up
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 
Example #15
Source File: defer.py    From learn_python3_spider with MIT License 4 votes vote down vote up
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