Python asyncio.iscoroutinefunction() Examples
The following are 30
code examples of asyncio.iscoroutinefunction().
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: rpc.py From aioamqp_consumer with MIT License | 6 votes |
def __init__( self, method, *, queue_name, queue_kwargs, exchange_name, exchange_kwargs, routing_key, packer, auto_reject, auto_reject_delay, ): self.method = method self.queue_name = queue_name self.queue_kwargs = queue_kwargs self.exchange_name = exchange_name self.exchange_kwargs = exchange_kwargs self.routing_key = routing_key self.packer = packer self.auto_reject = auto_reject self.auto_reject_delay = auto_reject_delay _fn = unpartial(self.method) self._method_is_coro = asyncio.iscoroutinefunction(_fn)
Example #2
Source File: conftest.py From aiohttp_admin with Apache License 2.0 | 6 votes |
def pytest_pyfunc_call(pyfuncitem): """ Run asyncio marked test functions in an event loop instead of a normal function call. """ if 'run_loop' in pyfuncitem.keywords: funcargs = pyfuncitem.funcargs loop = funcargs['loop'] testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames} if not asyncio.iscoroutinefunction(pyfuncitem.obj): func = asyncio.coroutine(pyfuncitem.obj) else: func = pyfuncitem.obj loop.run_until_complete(func(**testargs)) return True
Example #3
Source File: kube_config.py From kubernetes_asyncio with Apache License 2.0 | 6 votes |
def load_gcp_token(self): if 'config' not in self._user['auth-provider']: self._user['auth-provider'].value['config'] = {} config = self._user['auth-provider']['config'] if (('access-token' not in config) or ('expiry' in config and _is_expired(config['expiry']))): if self._get_google_credentials is not None: if asyncio.iscoroutinefunction(self._get_google_credentials): credentials = await self._get_google_credentials() else: credentials = self._get_google_credentials() else: credentials = await google_auth_credentials(config) config.value['access-token'] = credentials.token config.value['expiry'] = credentials.expiry if self._config_persister: self._config_persister(self._config.value) self.token = "Bearer %s" % config['access-token'] return self.token
Example #4
Source File: protocol.py From huawei-lpv2 with MIT License | 6 votes |
def check_result(func): def raise_if_unsuccessful(command: Command): result = process_result(command) if result is not None and result != RESULT_SUCCESS: raise ValueError(f"result code does not indicate success: {result}") if asyncio.iscoroutinefunction(func): @wraps(func) async def wrapper(*args, **kwargs): command = await func(*args, **kwargs) logger.debug(f"Checking coroutine result: {command}...") raise_if_unsuccessful(command) return command return wrapper else: @wraps(func) def wrapper(*args, **kwargs): command = args[0] if isinstance(args[0], Command) else args[1] # support bound methods logger.debug(f"Checking function or bound method input: {command}...") assert isinstance(command, Command) raise_if_unsuccessful(command) return func(*args, **kwargs) return wrapper
Example #5
Source File: streaming.py From vk-requests with MIT License | 6 votes |
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 #6
Source File: tools.py From python-insteonplm with MIT License | 6 votes |
def _exec_cmd(self, cmd): return_val = None func = None if cmd.strip(): command, arg = self._parse_cmd(cmd) if command is None: return self._invalid(cmd) if command == "": return self._invalid(cmd) try: func = getattr(self, "do_" + command) except AttributeError: func = self._invalid arg = str(cmd) except KeyboardInterrupt: func = None # func(arg) if func: if asyncio.iscoroutinefunction(func): return_val = await func(arg) else: return_val = func(arg) return return_val # pylint: disable=no-self-use
Example #7
Source File: loop.py From switchio with Mozilla Public License 2.0 | 6 votes |
def add_coroutine(self, evname, ident, coro, *args, **kwargs): """Register a coroutine which will be scheduled when events of type ``evname`` are received. The coroutine will be scheduled only when the value of ``ident`` matches one of the ``self.app_id_headers`` values read from the event. This allows for triggering certain coroutines on specific session state/inputs. """ prepend = kwargs.pop('prepend', False) if not asyncio.iscoroutinefunction(coro): return False if args or kwargs: coro = partial(coro, *args, **kwargs) d = self.coroutines.setdefault(ident, {}).setdefault(evname, deque()) getattr(d, 'appendleft' if prepend else 'append')(coro) return True
Example #8
Source File: server.py From lrrbot with Apache License 2.0 | 6 votes |
def add_url_rule(self, rule, endpoint, view_func, **options): # Cache the wrapper functions so Flask doesn't complain. if asyncio.iscoroutinefunction(view_func): if view_func not in self.__wrapped_view_funcs: @functools.wraps(view_func) def inner(*args, **kwargs): return asyncio.get_event_loop().run_until_complete(view_func(*args, **kwargs)) self.__wrapped_view_funcs[view_func] = inner func = inner if view_func in flaskext.csrf._exempt_views: flaskext.csrf.csrf_exempt(func) else: func = self.__wrapped_view_funcs[view_func] else: func = view_func return super().add_url_rule(rule, endpoint, func, **options)
Example #9
Source File: core.py From discord.py with MIT License | 6 votes |
def error(self, coro): """A decorator that registers a coroutine as a local error handler. A local error handler is an :func:`.on_command_error` event limited to a single command. However, the :func:`.on_command_error` is still invoked afterwards as the catch-all. Parameters ----------- coro: :ref:`coroutine <coroutine>` The coroutine to register as the local error handler. Raises ------- TypeError The coroutine passed is not actually a coroutine. """ if not asyncio.iscoroutinefunction(coro): raise TypeError('The error handler must be a coroutine.') self.on_error = coro return coro
Example #10
Source File: UMRDriver.py From UnifiedMessageRelay with MIT License | 6 votes |
def api_call(platform: str, api_name: str, *args, **kwargs): """ fast api call :param platform: driver alias :param api_name: name of the api :param args: positional args to pass :param kwargs: keyword args to pass :return: None for API not found, api result for successful calling api result can be any or asyncio.Future, for Future type use result.result() to get the actual result """ driver = driver_lookup(platform) if not driver: logger.error(f'Due to driver "{platform}" not found, "{api_name}" is ignored') return func = getattr(driver, api_name) if not func: return if iscoroutinefunction(func): return await func(*args, **kwargs) else: return func(*args, **kwargs) # endregion
Example #11
Source File: worker.py From bioconda-utils with MIT License | 6 votes |
def bind(self, app=None): """Intercept binding of task to (celery) app Here we take the half-finished generated Task class and replace the async run method with a sync run method that executes the original method inside the asyncio loop. """ if asyncio.iscoroutinefunction(self.run): # only for async funcs @wraps(self.run) def sync_run(*args, **kwargs): largs = list(args) # need list so that pre-run can modify self.loop.run_until_complete(self.async_pre_run(largs, kwargs)) return self.loop.run_until_complete(self._async_run(*largs, **kwargs)) # swap run method with wrapper defined above self._async_run, self.run = self.run, sync_run if not self.loop.is_running(): self.loop.run_until_complete(self.async_init()) super().bind(app)
Example #12
Source File: events.py From backend.ai-manager with GNU Lesser General Public License v3.0 | 6 votes |
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 #13
Source File: events.py From backend.ai-manager with GNU Lesser General Public License v3.0 | 6 votes |
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 #14
Source File: activate_async.py From pook with MIT License | 6 votes |
def activate_async(fn, _engine): """ Async version of activate decorator Arguments: fn (function): function that be wrapped by decorator. _engine (Engine): pook engine instance Returns: function: decorator wrapper function. """ @coroutine @functools.wraps(fn) def wrapper(*args, **kw): _engine.activate() try: if iscoroutinefunction(fn): yield from fn(*args, **kw) # noqa else: fn(*args, **kw) finally: _engine.disable() return wrapper
Example #15
Source File: utils.py From ariadne with BSD 3-Clause "New" or "Revised" License | 6 votes |
def convert_kwargs_to_snake_case(func: Callable) -> Callable: def convert_to_snake_case(d: Dict) -> Dict: converted: Dict = {} for k, v in d.items(): if isinstance(v, dict): v = convert_to_snake_case(v) if isinstance(v, list): v = [convert_to_snake_case(i) if isinstance(i, dict) else i for i in v] converted[convert_camel_case_to_snake(k)] = v return converted if asyncio.iscoroutinefunction(func): @wraps(func) async def async_wrapper(*args: Any, **kwargs: Any) -> Any: return await func(*args, **convert_to_snake_case(kwargs)) return async_wrapper @wraps(func) def wrapper(*args: Any, **kwargs: Any) -> Any: return func(*args, **convert_to_snake_case(kwargs)) return wrapper
Example #16
Source File: stream2.py From alpaca-trade-api-python with Apache License 2.0 | 5 votes |
def register(self, channel_pat, func: Callable, symbols=None): if not asyncio.iscoroutinefunction(func): raise ValueError('handler must be a coroutine function') if isinstance(channel_pat, str): channel_pat = re.compile(channel_pat) self._handlers[channel_pat] = func self._handler_symbols[func] = symbols
Example #17
Source File: stream2.py From alpaca-trade-api-python with Apache License 2.0 | 5 votes |
def register(self, channel_pat, func: Callable, symbols=None): if not asyncio.iscoroutinefunction(func): raise ValueError('handler must be a coroutine function') if isinstance(channel_pat, str): channel_pat = re.compile(channel_pat) self._handlers[channel_pat] = func self._handler_symbols[func] = symbols if self.trading_ws: self.trading_ws.register(channel_pat, func, symbols) if self.data_ws: self.data_ws.register(channel_pat, func, symbols)
Example #18
Source File: worker.py From arq with MIT License | 5 votes |
def func( coroutine: Union[str, Function, 'WorkerCoroutine'], *, name: Optional[str] = None, keep_result: Optional['SecondsTimedelta'] = None, timeout: Optional['SecondsTimedelta'] = None, max_tries: Optional[int] = None, ) -> Function: """ Wrapper for a job function which lets you configure more settings. :param coroutine: coroutine function to call, can be a string to import :param name: name for function, if None, ``coroutine.__qualname__`` is used :param keep_result: duration to keep the result for, if 0 the result is not kept :param timeout: maximum time the job should take :param max_tries: maximum number of tries allowed for the function, use 1 to prevent retrying """ if isinstance(coroutine, Function): return coroutine if isinstance(coroutine, str): name = name or coroutine coroutine_: 'WorkerCoroutine' = import_string(coroutine) else: coroutine_ = coroutine assert asyncio.iscoroutinefunction(coroutine_), f'{coroutine_} is not a coroutine function' timeout = to_seconds(timeout) keep_result = to_seconds(keep_result) return Function(name or coroutine_.__qualname__, coroutine_, timeout, keep_result, max_tries)
Example #19
Source File: consumers.py From djangochannelsrestframework with MIT License | 5 votes |
def ensure_async(method: typing.Callable): if asyncio.iscoroutinefunction(method): return method return database_sync_to_async(method)
Example #20
Source File: base.py From deal with MIT License | 5 votes |
def __call__(self, function: _CallableType) -> _CallableType: """ Step 2. Return wrapped function. """ self.function = function def wrapped(*args, **kwargs): if self.enabled: return self.patched_function(*args, **kwargs) else: return function(*args, **kwargs) async def async_wrapped(*args, **kwargs): if self.enabled: return await self.async_patched_function(*args, **kwargs) else: return await function(*args, **kwargs) def wrapped_generator(*args, **kwargs): if self.enabled: yield from self.patched_generator(*args, **kwargs) else: yield from function(*args, **kwargs) if iscoroutinefunction(function): new_callable = update_wrapper(async_wrapped, function) elif inspect.isgeneratorfunction(function): new_callable = update_wrapper(wrapped_generator, function) else: new_callable = update_wrapper(wrapped, function) return new_callable # type: ignore
Example #21
Source File: paginator.py From modmail with GNU Affero General Public License v3.0 | 5 votes |
def inverse_button(emoji: str = None, *, try_remove=False, position: int = 666): """A decorator that adds an inverted button to your interactive session class. The inverse button will work when a reaction is unpressed. Parameters ----------- emoji: str The emoji to use as a button. This could be a unicode endpoint or in name:id format, for custom emojis. position: int The position to inject the button into. Raises ------- TypeError The button callback is not a coroutine. """ def deco(func): if not asyncio.iscoroutinefunction(func): raise TypeError("Button callback must be a coroutine.") if hasattr(func, "__button__"): button = func.__button__ button._inverse_callback = func return func func.__button__ = Button(emoji=emoji, inverse_callback=func, position=position, try_remove=try_remove) return func return deco
Example #22
Source File: decorators.py From djangochannelsrestframework with MIT License | 5 votes |
def action(atomic=None, **kwargs): """ Mark a method as an action. """ def decorator(func): if atomic is None: _atomic = getattr(settings, "ATOMIC_REQUESTS", False) else: _atomic = atomic func.action = True func.kwargs = kwargs if asyncio.iscoroutinefunction(func): if _atomic: raise ValueError("Only synchronous actions can be atomic") return func if _atomic: # wrap function in atomic wrapper func = transaction.atomic(func) @wraps(func) async def async_f(self: AsyncAPIConsumer, *args, **_kwargs): result, status = await database_sync_to_async(func)(self, *args, **_kwargs) return result, status async_f.action = True async_f.kwargs = kwargs async_f.__name__ = func.__name__ return async_f return decorator
Example #23
Source File: compat.py From aiohttp_apiset with Apache License 2.0 | 5 votes |
def __init__(self, method, handler, *, expect_handler=None, resource=None): if expect_handler is None: expect_handler = _defaultExpectHandler assert asyncio.iscoroutinefunction(expect_handler), \ 'Coroutine is expected, got {!r}'.format(expect_handler) method = method.upper() if not HTTP_METHOD_RE.match(method): raise ValueError("{} is not allowed HTTP method".format(method)) assert callable(handler), handler if asyncio.iscoroutinefunction(handler): pass elif inspect.isgeneratorfunction(handler): warnings.warn("Bare generators are deprecated, " "use @coroutine wrapper", DeprecationWarning) elif isinstance(handler, type) and issubclass(handler, AbstractView): pass else: @functools.wraps(handler) async def handler_wrapper(*args, **kwargs): result = old_handler(*args, **kwargs) if asyncio.iscoroutine(result): result = await result return result old_handler = handler handler = handler_wrapper self._method = method self._handler = handler self._expect_handler = expect_handler self._resource = resource
Example #24
Source File: jinja2.py From aiohttp_apiset with Apache License 2.0 | 5 votes |
def template(template_name, *, app_key=APP_KEY, encoding='utf-8', status=200): """ Decorator compatible with aiohttp_apiset router """ def wrapper(func): @functools.wraps(func) async def wrapped(*args, **kwargs): if asyncio.iscoroutinefunction(func): coro = func else: coro = asyncio.coroutine(func) context = await coro(*args, **kwargs) if isinstance(context, web.StreamResponse): return context if 'request' in kwargs: request = kwargs['request'] elif not args: request = None warnings.warn("Request not detected") elif isinstance(args[0], AbstractView): request = args[0].request else: request = args[-1] response = render_template(template_name, request, context, app_key=app_key, encoding=encoding) response.set_status(status) return response return wrapped return wrapper
Example #25
Source File: cached_property.py From deepWordBug with Apache License 2.0 | 5 votes |
def __get__(self, obj, cls): if obj is None: return self if asyncio and asyncio.iscoroutinefunction(self.func): return self._wrap_in_coroutine(obj) value = obj.__dict__[self.func.__name__] = self.func(obj) return value
Example #26
Source File: timer_service.py From loopchain with Apache License 2.0 | 5 votes |
def off(self, off_type): """turn off timer by type :param off_type: type of reason to turn off timer """ if off_type is OffType.time_out: logging.debug(f'timer({self.target}) is turned off by timeout') if asyncio.iscoroutinefunction(self.__callback): self.try_coroutine() else: self.try_func()
Example #27
Source File: atomicpuppy.py From atomicpuppy with MIT License | 5 votes |
def _ensure_coroutine_function(func): """Return a coroutine function. func: either a coroutine function or a regular function Note a coroutine function is not a coroutine! """ if asyncio.iscoroutinefunction(func): return func else: async def coroutine_function(evt): return func(evt) return coroutine_function
Example #28
Source File: decorators.py From Pyrlang with Apache License 2.0 | 5 votes |
def __call__(self, fun): if not asyncio.iscoroutinefunction(fun): LOG.debug("function %s is a handle_%s and is not async", fun, self.handler_type) fun = async_wrapper_factory(fun) fun._gen_handler = self.handler_type run_fun = self._pattern_run_fun_factory(fun) fun._gen_pattern = Pattern(self.pattern, run_fun) fun._gen_order = self.order return fun
Example #29
Source File: server.py From Pyrlang with Apache License 2.0 | 5 votes |
def process_loop(self): """ Polls inbox in an endless loop. .. note:: This will not be executed if the process was constructed with ``passive=True`` (the default). Passive processes should read their inbox directly from ``self.inbox_``. """ self.state = 'running' while not self.is_exiting_: # If any messages have been handled recently, do not sleep # Else if no messages, sleep for some short time LOG.debug("jso: waiting for inbox data") msg = await self.receive() if type(msg) != tuple or len(msg) != 2: LOG.debug("Got unhandled msg: %s", msg) continue LOG.debug("got msg = %s", msg) fun, args = msg # todo: make this if thing in meta class so that we only evaluate # this once import asyncio if asyncio.iscoroutinefunction(fun): # since fun will be returned by a function that only have access # to the Class rather than the instance, we have to send `self` # as an argument await fun(self, args) else: fun(self, args) LOG.debug("Process %s process_loop stopped", self.pid_) self.state = 'exiting'
Example #30
Source File: __init__.py From aiocron with MIT License | 5 votes |
def wrap_func(func): """wrap in a coroutine""" if not asyncio.iscoroutinefunction(func): return asyncio.coroutine(func) return func