Python asyncio.iscoroutine() Examples

The following are 30 code examples of asyncio.iscoroutine(). 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 asyncio , or try the search function .
Example #1
Source File: test_aio.py    From prometheus-async with Apache License 2.0 6 votes vote down vote up
def test_decorator(self, fo, patch_timer):
        """
        time works with asyncio results functions.
        """

        @aio.time(fo)
        async def func():
            await asyncio.sleep(0)
            return 42

        rv = func()

        assert asyncio.iscoroutine(rv)
        assert [] == fo._observed

        rv = await rv

        assert [1] == fo._observed
        assert 42 == rv 
Example #2
Source File: events.py    From backend.ai-manager with GNU Lesser General Public License v3.0 6 votes vote down vote up
def dispatch_subscribers(self, event_name: str, agent_id: AgentId,
                                   args: Tuple[Any, ...] = tuple()) -> None:
        log_fmt = 'DISPATCH_SUBSCRIBERS(ev:{}, ag:{})'
        log_args = (event_name, agent_id)
        if self.root_app['config']['debug']['log-events']:
            log.debug(log_fmt, *log_args)
        scheduler = get_scheduler_from_app(self.root_app)
        for subscriber in self.subscribers[event_name]:
            cb = subscriber.callback
            try:
                if asyncio.iscoroutine(cb):
                    await scheduler.spawn(cb)
                elif asyncio.iscoroutinefunction(cb):
                    await scheduler.spawn(cb(subscriber.context, agent_id, event_name, *args))
                else:
                    cb = functools.partial(cb, subscriber.context, agent_id, event_name, *args)
                    self.loop.call_soon(cb)
            except asyncio.CancelledError:
                raise
            except Exception:
                log.exception(log_fmt + ': unexpected-error', *log_args) 
Example #3
Source File: app.py    From datasette with Apache License 2.0 6 votes vote down vote up
def get_canned_queries(self, database_name, actor):
        queries = self.metadata("queries", database=database_name, fallback=False) or {}
        for more_queries in pm.hook.canned_queries(
            datasette=self, database=database_name, actor=actor,
        ):
            if callable(more_queries):
                more_queries = more_queries()
            if asyncio.iscoroutine(more_queries):
                more_queries = await more_queries
            queries.update(more_queries or {})
        # Fix any {"name": "select ..."} queries to be {"name": {"sql": "select ..."}}
        for key in queries:
            if not isinstance(queries[key], dict):
                queries[key] = {"sql": queries[key]}
            # Also make sure "name" is available:
            queries[key]["name"] = key
        return queries 
Example #4
Source File: resources_cmd.py    From stig with GNU General Public License v3.0 6 votes vote down vote up
def assert_completion_candidates(self, cmdcls, args, exp_cands, exp_curarg_seps=()):
        cands = cmdcls.completion_candidates(args)
        if asyncio.iscoroutine(cands):
            cands = await cands

        if cands is None:
            self.assertIs(None, exp_cands)
        else:
            if cands and not isinstance(cands[0], str):
                self.assertEqual(tuple(tuple(subcands) for subcands in cands),
                                 tuple(sorted(exp_cands)))
                for subcands,exp_seps in zip(cands,exp_curarg_seps):
                    self.assertEqual(subcands.curarg_seps, exp_seps)
            else:
                self.assertEqual(tuple(cands), tuple(sorted(exp_cands)))
                self.assertEqual(cands.curarg_seps, exp_curarg_seps) 
Example #5
Source File: generate_json_api.py    From lbry-sdk with MIT License 6 votes vote down vote up
def __call__(self, title, *command):
        parser = get_argument_parser()
        args, command_args = parser.parse_known_args(command)

        api_method_name = args.api_method_name
        parsed = docopt(args.doc, command_args)
        kwargs = set_kwargs(parsed)
        for k, v in kwargs.items():
            if v and isinstance(v, str) and (v[0], v[-1]) == ('"', '"'):
                kwargs[k] = v[1:-1]
        params = json.dumps({"method": api_method_name, "params": kwargs})

        method = getattr(self.test.daemon, f'jsonrpc_{api_method_name}')
        result = method(**kwargs)
        if asyncio.iscoroutine(result):
            result = await result
        output = jsonrpc_dumps_pretty(result, ledger=self.test.daemon.ledger)
        self.examples.setdefault(api_method_name, []).append({
            'title': title,
            'curl': f"curl -d'{params}' http://localhost:5279/",
            'lbrynet': 'lbrynet ' + ' '.join(command),
            'python': f'requests.post("http://localhost:5279", json={params}).json()',
            'output': output.strip()
        })
        return json.loads(output)['result'] 
Example #6
Source File: runners.py    From stories with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __call__(self, *args, **kwargs):
        import asyncio

        _stories.mounted.instrumented = True
        try:
            c = self.story(*args, **kwargs)
        finally:
            _stories.mounted.instrumented = False
        if not asyncio.iscoroutine(c):
            raise Exception("A coroutine executor expected")  # pragma: no cover
        try:
            c.send(None)
        except StopIteration as error:
            return error.value
        else:
            raise Exception("A coroutine does not return")  # pragma: no cover 
Example #7
Source File: events.py    From backend.ai-manager with GNU Lesser General Public License v3.0 6 votes vote down vote up
def dispatch_consumers(self, event_name: str, agent_id: AgentId,
                                 args: Tuple[Any, ...] = tuple()) -> None:
        log_fmt = 'DISPATCH_CONSUMERS(ev:{}, ag:{})'
        log_args = (event_name, agent_id)
        if self.root_app['config']['debug']['log-events']:
            log.debug(log_fmt, *log_args)
        scheduler = get_scheduler_from_app(self.root_app)
        for consumer in self.consumers[event_name]:
            cb = consumer.callback
            try:
                if asyncio.iscoroutine(cb):
                    await scheduler.spawn(cb)
                elif asyncio.iscoroutinefunction(cb):
                    await scheduler.spawn(cb(consumer.context, agent_id, event_name, *args))
                else:
                    cb = functools.partial(cb, consumer.context, agent_id, event_name, *args)
                    self.loop.call_soon(cb)
            except asyncio.CancelledError:
                raise
            except Exception:
                log.exception(log_fmt + ': unexpected-error', *log_args) 
Example #8
Source File: unsync.py    From unsync with MIT License 6 votes vote down vote up
def __init__(self, future=None):
        def callback(source, target):
            try:
                asyncio.futures._chain_future(source, target)
            except Exception as exc:
                if self.concurrent_future.set_running_or_notify_cancel():
                    self.concurrent_future.set_exception(exc)
                raise

        if asyncio.iscoroutine(future):
            future = asyncio.ensure_future(future, loop=unsync.loop)
        if isinstance(future, concurrent.futures.Future):
            self.concurrent_future = future
            self.future = asyncio.Future(loop=unsync.loop)
            self.future._loop.call_soon_threadsafe(callback, self.concurrent_future, self.future)
        else:
            self.future = future or asyncio.Future(loop=unsync.loop)
            self.concurrent_future = concurrent.futures.Future()
            self.future._loop.call_soon_threadsafe(callback, self.future, self.concurrent_future) 
Example #9
Source File: application.py    From aiosip with Apache License 2.0 6 votes vote down vote up
def finish(self):
        callbacks = self._finish_callbacks
        self._finish_callbacks = []

        for (cb, args, kwargs) in callbacks:
            try:
                res = cb(self, *args, **kwargs)
                if (asyncio.iscoroutine(res) or
                        isinstance(res, asyncio.Future)):
                    yield from res
            except Exception as exc:
                self.loop.call_exception_handler({
                    'message': "Error in finish callback",
                    'exception': exc,
                    'application': self,
                }) 
Example #10
Source File: middlewares.py    From apidaora with MIT License 6 votes vote down vote up
def __call__(self, request: Request, response: Response) -> None:
        task: Any
        response_tasks: Union[
            Iterable[Callable[[], None]], Callable[[], None]
        ] = []

        if response.ctx:
            response_tasks = response.ctx.get(
                'background_tasks', response_tasks
            )

        if response_tasks and not isinstance(response_tasks, Iterable):
            response_tasks = (response_tasks,)

        for task in response_tasks:
            if asyncio.iscoroutinefunction(task):
                task = task()

            elif not asyncio.iscoroutine(task):
                future = self.executor.submit(task)
                future.add_done_callback(self.done_callback)
                return

            task = asyncio.create_task(task)
            task.add_done_callback(self.done_callback) 
Example #11
Source File: aio.py    From txaio with MIT License 6 votes vote down vote up
def as_future(self, fun, *args, **kwargs):
        try:
            res = fun(*args, **kwargs)
        except Exception:
            return create_future_error(create_failure())
        else:
            if isinstance(res, Future):
                return res
            elif iscoroutine(res):
                return self._loop.create_task(res)
            elif isinstance(res, AsyncGeneratorType):
                raise RuntimeError(
                    "as_future() received an async generator function; does "
                    "'{}' use 'yield' when you meant 'await'?".format(
                        str(fun)
                    )
                )
            else:
                return create_future_success(res) 
Example #12
Source File: test_pep492.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_iscoroutine(self):
        async def foo(): pass

        f = foo()
        try:
            self.assertTrue(asyncio.iscoroutine(f))
        finally:
            f.close() # silence warning

        # Test that asyncio.iscoroutine() uses collections.abc.Coroutine
        class FakeCoro:
            def send(self, value): pass
            def throw(self, typ, val=None, tb=None): pass
            def close(self): pass
            def __await__(self): yield

        self.assertTrue(asyncio.iscoroutine(FakeCoro())) 
Example #13
Source File: steam.py    From RubyRoseBot with Mozilla Public License 2.0 6 votes vote down vote up
def steamdebug(self, ctx, *, shit: str):
        """This is the part where I make 20,000 typos before I get it right"""
        # "what the fuck is with your variable naming" - EJH2
        # seth seriously what the fuck - Robin
        import asyncio
        import os
        import random
        import re
        from datetime import datetime, timedelta
        try:
            rebug = eval(shit)
            if asyncio.iscoroutine(rebug):
                rebug = await rebug
            await ctx.send(py.format(rebug))
        except Exception as damnit:
            await ctx.send(py.format("{}: {}".format(type(damnit).__name__, damnit))) 
Example #14
Source File: information.py    From RubyRoseBot with Mozilla Public License 2.0 6 votes vote down vote up
def infodebug(self, ctx, *, shit:str):
        """This is the part where I make 20,000 typos before I get it right"""
        # "what the fuck is with your variable naming" - EJH2
        # seth seriously what the fuck - Robin
        import asyncio
        import os
        import random
        import re
        from datetime import datetime, timedelta
        try:
            rebug = eval(shit)
            if asyncio.iscoroutine(rebug):
                rebug = await rebug
            await ctx.send(py.format(rebug))
        except Exception as damnit:
            await ctx.send(py.format("{}: {}".format(type(damnit).__name__, damnit))) 
Example #15
Source File: community.py    From py-ipv8 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def on_packet(self, packet, warn_unknown=True):
        source_address, data = packet
        probable_peer = self.network.get_verified_by_address(source_address)
        if probable_peer:
            probable_peer.last_response = time()
        if self._prefix != data[:22]:
            return
        msg_id = chr(ord(data[22:23]))
        if msg_id in self.decode_map:
            handler = self.decode_map[msg_id]
            try:
                result = handler(source_address, data)
                if iscoroutine(result):
                    self.register_anonymous_task('on_packet', ensure_future(result), ignore=(Exception,))
            except Exception:
                self.logger.error("Exception occurred while handling packet!\n"
                                  + ''.join(format_exception(*sys.exc_info())))
        elif warn_unknown:
            self.logger.warning("Received unknown message: %d from (%s, %d)", ord(msg_id), *source_address) 
Example #16
Source File: hidden_services.py    From py-ipv8 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def on_linked_e2e(self, source_address, payload, circuit_id):
        if not self.request_cache.has(u"link-request", payload.identifier):
            self.logger.warning("Invalid linked-e2e identifier")
            return

        cache = self.request_cache.pop(u"link-request", payload.identifier)
        circuit = cache.circuit
        circuit.e2e = True
        circuit.hs_session_keys = cache.hs_session_keys
        callback = self.e2e_callbacks.get(cache.info_hash, None)
        if callback:
            result = callback((self.circuit_id_to_ip(circuit.circuit_id), CIRCUIT_ID_PORT))
            if iscoroutine(result):
                self.register_anonymous_task('e2e_callback', result)
        else:
            self.logger.error('On linked e2e: could not find download for %s!', cache.info_hash) 
Example #17
Source File: verifier.py    From asap-authentication-python with MIT License 6 votes vote down vote up
def verify_jwt(self, a_jwt, audience, leeway=0, **requests_kwargs):
        """Verify if the token is correct

        Returns:
             dict: the claims of the given jwt if verification is successful.

        Raises:
            ValueError: if verification failed.
        """
        key_identifier = key._get_key_id_from_jwt_header(a_jwt)

        public_key = self._retrieve_pub_key(key_identifier, requests_kwargs)
        if asyncio.iscoroutine(public_key):
            public_key = await public_key

        return self._decode_jwt(
            a_jwt, key_identifier, public_key,
            audience=audience, leeway=leeway) 
Example #18
Source File: streaming.py    From vk-requests with MIT License 6 votes vote down vote up
def consumer(self, fn):
        """Consumer decorator

        :param fn: coroutine consumer function

        Example:

        >>> api = StreamingAPI('my_service_key')
        >>> stream = api.get_stream()

        >>> @stream.consumer
        >>> @asyncio.coroutine
        >>> def handle_event(payload):
        >>>     print(payload)

        """
        if self._consumer_fn is not None:
            raise ValueError('Consumer function is already defined for this '
                             'Stream instance')
        if not any([asyncio.iscoroutine(fn), asyncio.iscoroutinefunction(fn)]):
            raise ValueError('Consumer function must be a coroutine')
        self._consumer_fn = fn 
Example #19
Source File: stream.py    From lbry-sdk with MIT License 5 votes vote down vote up
def _notify_and_ensure_future(self, notify):
        tasks = []
        for subscription in self._iterate_subscriptions:
            maybe_coroutine = notify(subscription)
            if asyncio.iscoroutine(maybe_coroutine):
                tasks.append(maybe_coroutine)
        if tasks:
            return asyncio.ensure_future(asyncio.wait(tasks))
        else:
            f = asyncio.get_event_loop().create_future()
            f.set_result(None)
            return f 
Example #20
Source File: test_tasks.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_coroutine_non_gen_function(self):
        @asyncio.coroutine
        def func():
            return 'test'

        self.assertTrue(asyncio.iscoroutinefunction(func))

        coro = func()
        self.assertTrue(asyncio.iscoroutine(coro))

        res = self.loop.run_until_complete(coro)
        self.assertEqual(res, 'test') 
Example #21
Source File: _tasks_async.py    From peeringdb-py with Apache License 2.0 5 votes vote down vote up
def __init__(self, coro, desc, loop=None):
        """
        Arguments:
            - coro: awaitable object
            - desc<tuple>: (Resource, key)
        """
        assert asyncio.iscoroutine(coro), coro
        self._desc = desc
        super().__init__(coro) 
Example #22
Source File: _mixin.py    From stig with GNU General Public License v3.0 5 votes vote down vote up
def _run_func_or_coro(self, func_or_coro):
        if asyncio.iscoroutinefunction(func_or_coro):
            await func_or_coro()
        elif asyncio.iscoroutine(func_or_coro):
            await func_or_coro
        elif func_or_coro is not None:
            func_or_coro() 
Example #23
Source File: async_util.py    From CloudBot with GNU General Public License v3.0 5 votes vote down vote up
def run_coroutine_threadsafe(coro, loop):
    """
    Runs a coroutine in a threadsafe manner
    :type coro: coroutine
    :type loop: asyncio.AbstractEventLoop
    """
    if not asyncio.iscoroutine(coro):
        raise TypeError('A coroutine object is required')

    if sys.version_info < (3, 5, 1):
        loop.call_soon_threadsafe(partial(wrap_future, coro, loop=loop))
    else:
        asyncio.run_coroutine_threadsafe(coro, loop) 
Example #24
Source File: async_util.py    From CloudBot with GNU General Public License v3.0 5 votes vote down vote up
def run_func_with_args(loop, func, arg_data, executor=None):
    if asyncio.iscoroutine(func):
        raise TypeError('A coroutine function or a normal, non-async callable are required')

    if asyncio.iscoroutinefunction(func):
        coro = call_with_args(func, arg_data)
    else:
        coro = loop.run_in_executor(executor, call_with_args, func, arg_data)

    return await coro 
Example #25
Source File: async_util.py    From CloudBot with GNU General Public License v3.0 5 votes vote down vote up
def run_func(loop, func, *args, **kwargs):
    part = partial(func, *args, **kwargs)
    if asyncio.iscoroutine(func) or asyncio.iscoroutinefunction(func):
        return await part()

    return await loop.run_in_executor(None, part) 
Example #26
Source File: __init__.py    From hangoutsbot with GNU Affero General Public License v3.0 5 votes vote down vote up
def start_asyncio_task(coroutine_function, *args, **kwargs):
    loop = asyncio.get_event_loop()
    if asyncio.iscoroutinefunction(coroutine_function):
        task = loop.create_task(coroutine_function(tracking.bot, *args, **kwargs))
    elif asyncio.iscoroutine(coroutine_function):
        task = loop.create_task(coroutine_function)
    else:
        raise RuntimeError("coroutine function must be supplied")
    asyncio.ensure_future(task).add_done_callback(asyncio_task_ended)
    tracking.register_asyncio_task(task)
    return task 
Example #27
Source File: tkinterface.py    From hwk-mirror with GNU General Public License v3.0 5 votes vote down vote up
def async_forward(self, request, *args, **kwargs):
        if hasattr(self.delegate, request):
            function = object.__getattribute__(self.delegate, request)
            assert callable(function) and asyncio.iscoroutine(function)
            await function(*args, **kwargs)
        else:
            raise NotImplementedError 
Example #28
Source File: tkinterface.py    From hwk-mirror with GNU General Public License v3.0 5 votes vote down vote up
def forward(self, request, *args, **kwargs):
        if hasattr(self.delegate, request):
            attribute = object.__getattribute__(self.delegate, request)
            if not callable(attribute):
                return attribute
            assert not asyncio.iscoroutine(attribute)
            return attribute(*args, **kwargs)
        else:
            raise NotImplementedError 
Example #29
Source File: testcase.py    From lbry-sdk with MIT License 5 votes vote down vote up
def doAsyncCleanups(self):  # pylint: disable=C0103
        outcome = self._outcome or _Outcome()
        while self._cleanups:
            function, args, kwargs = self._cleanups.pop()
            with outcome.testPartExecutor(self):
                maybe_coroutine = function(*args, **kwargs)
                if asyncio.iscoroutine(maybe_coroutine):
                    self.loop.run_until_complete(maybe_coroutine) 
Example #30
Source File: scheduler.py    From calebj-cogs with GNU General Public License v3.0 5 votes vote down vote up
def get_prefix(self, msg, content=None):
        prefixes = self.bot.command_prefix
        if callable(prefixes):
            prefixes = prefixes(self.bot, msg)

            if asyncio.iscoroutine(prefixes):
                prefixes = await prefixes

        content = content or msg.content

        for p in prefixes:
            if content.startswith(p):
                return p

        return None