本文整理匯總了Python中asyncio.iscoroutinefunction方法的典型用法代碼示例。如果您正苦於以下問題:Python asyncio.iscoroutinefunction方法的具體用法?Python asyncio.iscoroutinefunction怎麽用?Python asyncio.iscoroutinefunction使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類asyncio
的用法示例。
在下文中一共展示了asyncio.iscoroutinefunction方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: dispatch_consumers
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import iscoroutinefunction [as 別名]
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)
示例2: dispatch_subscribers
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import iscoroutinefunction [as 別名]
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)
示例3: error
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import iscoroutinefunction [as 別名]
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
示例4: check_result
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import iscoroutinefunction [as 別名]
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
示例5: add_url_rule
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import iscoroutinefunction [as 別名]
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)
示例6: __init__
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import iscoroutinefunction [as 別名]
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)
示例7: pytest_pyfunc_call
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import iscoroutinefunction [as 別名]
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
示例8: bind
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import iscoroutinefunction [as 別名]
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)
示例9: activate_async
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import iscoroutinefunction [as 別名]
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
示例10: convert_kwargs_to_snake_case
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import iscoroutinefunction [as 別名]
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
示例11: api_call
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import iscoroutinefunction [as 別名]
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
示例12: load_gcp_token
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import iscoroutinefunction [as 別名]
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
示例13: consumer
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import iscoroutinefunction [as 別名]
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
示例14: _exec_cmd
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import iscoroutinefunction [as 別名]
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
示例15: add_coroutine
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import iscoroutinefunction [as 別名]
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