Python源码示例:asyncio.iscoroutinefunction()
示例1
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
示例16
def is_coroutine_function(func: Any) -> bool:
# Python < 3.8 does not correctly determine partially wrapped
# coroutine functions are coroutine functions, hence the need for
# this to exist. Code taken from CPython.
if sys.version_info >= (3, 8):
return asyncio.iscoroutinefunction(func)
else:
# Note that there is something special about the CoroutineMock
# such that it isn't determined as a coroutine function
# without an explicit check.
try:
from asynctest.mock import CoroutineMock
if isinstance(func, CoroutineMock):
return True
except ImportError:
# Not testing, no asynctest to import
pass
while inspect.ismethod(func):
func = func.__func__
while isinstance(func, functools.partial):
func = func.func
if not inspect.isfunction(func):
return False
result = bool(func.__code__.co_flags & inspect.CO_COROUTINE)
return result or getattr(func, "_is_coroutine", None) is asyncio.coroutines._is_coroutine
示例17
def test_ensure_coroutine() -> None:
def sync_func() -> None:
pass
async def async_func() -> None:
pass
sync_wrapped = ensure_coroutine(sync_func)
assert asyncio.iscoroutinefunction(sync_wrapped)
assert sync_wrapped._quart_async_wrapper # type: ignore
async_wrapped = ensure_coroutine(async_func)
assert async_wrapped is async_func
示例18
def __init__(self, anonymous_handler):
if not iscoroutinefunction(anonymous_handler):
raise TypeError(
"AnonymousReceiveMiddleware must be instantiated with a valid coroutine function."
)
self._to_call = anonymous_handler
示例19
def _run_hooks(self, hooks):
coros = []
while len(hooks):
task = hooks.pop()
if asyncio.iscoroutinefunction(task):
coros.append(task(self))
else:
task(self)
await asyncio.gather(*coros)
示例20
def __del__(self):
if self._auto_created_session:
# aiohttp v3.0 has made ClientSession.close a coroutine,
# so we check whether it is one here and register it
# to run appropriately at exit
if asyncio.iscoroutinefunction(self._session.close):
asyncio.get_event_loop().run_until_complete(
self._session.close()
)
else:
self._session.close()
示例21
def wrap_callback(self, callback):
if not asyncio.iscoroutinefunction(callback):
callback = self._sync_callback_adapter(callback)
return callback
示例22
def __getattr__(self, item):
value = getattr(self.__response, item)
if asyncio.iscoroutinefunction(value):
return ThreadedCoroutine(value)
return value
示例23
def create_test(
endpoint: Endpoint, test: Callable, settings: Optional[hypothesis.settings] = None, seed: Optional[int] = None
) -> Callable:
"""Create a Hypothesis test."""
hook_dispatcher = getattr(test, "_schemathesis_hooks", None)
strategy = endpoint.as_strategy(hooks=hook_dispatcher)
wrapped_test = hypothesis.given(case=strategy)(test)
if seed is not None:
wrapped_test = hypothesis.seed(seed)(wrapped_test)
if asyncio.iscoroutinefunction(test):
wrapped_test.hypothesis.inner_test = make_async_test(test) # type: ignore
if settings is not None:
wrapped_test = settings(wrapped_test)
return add_examples(wrapped_test, endpoint, hook_dispatcher=hook_dispatcher)
示例24
def _check_coroutine(func):
if not asyncio.iscoroutinefunction(func):
raise TypeError("%s needs to be a coroutine" % str(func))
示例25
def event(self, coro):
"""A decorator that registers an event to listen to.
You can find more info about the events on the :ref:`documentation below <discord-api-events>`.
The events must be a :ref:`coroutine <coroutine>`, if not, :exc:`TypeError` is raised.
Example
---------
.. code-block:: python3
@client.event
async def on_ready():
print('Ready!')
Raises
--------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError('event registered must be a coroutine function')
setattr(self, coro.__name__, coro)
log.debug('%s has successfully been registered as an event', coro.__name__)
return coro
示例26
def before_invoke(self, coro):
"""A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is
called. This makes it a useful function to set up database
connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a :class:`.Context`.
See :meth:`.Bot.before_invoke` for more info.
Parameters
-----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the pre-invoke hook.
Raises
-------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError('The pre-invoke hook must be a coroutine.')
self._before_invoke = coro
return coro
示例27
def after_invoke(self, coro):
"""A decorator that registers a coroutine as a post-invoke hook.
A post-invoke hook is called directly after the command is
called. This makes it a useful function to clean-up database
connections or any type of clean up required.
This post-invoke hook takes a sole parameter, a :class:`.Context`.
See :meth:`.Bot.after_invoke` for more info.
Parameters
-----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the post-invoke hook.
Raises
-------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError('The post-invoke hook must be a coroutine.')
self._after_invoke = coro
return coro
示例28
def before_invoke(self, coro):
"""A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is
called. This makes it a useful function to set up database
connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a :class:`.Context`.
.. note::
The :meth:`~.Bot.before_invoke` and :meth:`~.Bot.after_invoke` hooks are
only called if all checks and argument parsing procedures pass
without error. If any check or argument parsing procedures fail
then the hooks are not called.
Parameters
-----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the pre-invoke hook.
Raises
-------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError('The pre-invoke hook must be a coroutine.')
self._before_invoke = coro
return coro
示例29
def add_listener(self, func, name=None):
"""The non decorator alternative to :meth:`.listen`.
Parameters
-----------
func: :ref:`coroutine <coroutine>`
The function to call.
name: Optional[:class:`str`]
The name of the event to listen for. Defaults to ``func.__name__``.
Example
--------
.. code-block:: python3
async def on_ready(): pass
async def my_message(message): pass
bot.add_listener(on_ready)
bot.add_listener(my_message, 'on_message')
"""
name = func.__name__ if name is None else name
if not asyncio.iscoroutinefunction(func):
raise TypeError('Listeners must be coroutines')
if name in self.extra_events:
self.extra_events[name].append(func)
else:
self.extra_events[name] = [func]
示例30
def is_coroutine(get_token):
try:
if asyncio.iscoroutinefunction(get_token.func):
return True
except AttributeError:
if asyncio.iscoroutinefunction(get_token):
return True
raise ValueError("get_token must be a coroutine function")