我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用asyncio.iscoroutine()。
def invoke(self, ctx): locals_ = locals().copy() try: load_function(self.code, dict(globals(), **ctx.bot.commands), locals_) except SyntaxError as err: traceback.print_exception(type(err), err, err.__traceback__) return 'SyntaxError: %s' % err try: ret = await locals_['evaluation'](ctx) if asyncio.iscoroutine(ret): ret = await ret elif ret in ctx.bot.commands.values(): ret = await ret() if asyncio.iscoroutinefunction(ret) else ret() except Exception as err: traceback.print_exception(type(err), err, err.__traceback__) return '%s: %s' % (type(err).__name__, err) else: return str(ret)
def send(self, group_resolver): coros = [] for i, g in self._signals: if not group_resolver.match(g): continue if asyncio.iscoroutinefunction(i): params = inspect.signature(i).parameters if 'context' in params: coro = i(self) else: coro = i() elif asyncio.iscoroutine(i): coro = i else: continue coros.append(coro) await self._context.wait_all(coros)
def handler(self, request): url = request.url params = dict(request.query) body = yield from request.read() body = json.loads(body.decode('utf-8')) if body else '' self.calls.append((request.method, url.path, body, params)) if url.path in self._responses: status, body = self._responses.pop(url.path) if asyncio.iscoroutine(body): body = yield from body else: status = 200 body = { 'method': request.method, 'params': params, 'path': url.path, 'body': body } out = json.dumps(body) return aiohttp.web.Response(body=out, status=status, content_type='application/json')
def debug(self, ctx, *, code): """Evaluates code Modified function, originally made by Rapptz""" code = code.strip('` ') python = '```py\n{}\n```' result = None local_vars = locals().copy() local_vars['bot'] = self.bot try: result = eval(code, globals(), local_vars) except Exception as e: await self.bot.say(python.format(type(e).__name__ + ': ' + str(e))) return if asyncio.iscoroutine(result): result = await result result = python.format(result) await self.bot.say(result)
def get_response(self, request): result = self.resolve_request(request) if result: controller_func, argv, kwargs = result else: controller_func = NotFoundController argv = [] kwargs = {} result = controller_func(request, *argv, **kwargs) if isinstance(result, BaseController): result = result.run() if asyncio.iscoroutine(result): result = await result return result
def inner_run(self): action = self.kwargs.get('action') if action: try: handler = getattr(self, action) except AttributeError: raise MethodNotAllowed() else: handler = self.handle self.before_handle() result = handler() if asyncio.iscoroutine(result): result = await result if not isinstance(result, Response): result = self.process_return_data(result) result = await self.create_response(result) return result
def log_headers_on_error(func=None): def wrap(fn): async def wrapper(self, *args, **kwargs): try: f = fn(self, *args, **kwargs) if asyncio.iscoroutine(f): f = await f return f except: if hasattr(self, 'request'): headers = "\n".join("{}: {}".format(header, value) for header, value in self.request.headers.items()) log.info("Headers for ERROR in {}\n{}\nData: {}".format(self.request.path, headers, self.request.body[:128])) raise return wrapper if func is not None: return wrap(func) else: return wrap
def commit(self, create_new_transaction=False): if self.transaction: try: callbacks = self.callbacks[:] self.callbacks.clear() rval = await self.transaction.commit() for callback in callbacks: f = callback() if asyncio.iscoroutine(f): await f return rval finally: if create_new_transaction: self.transaction = self.connection.transaction() await self.transaction.start() else: self.done = True self.transaction = None else: raise DatabaseError("No transaction to commit")
def cmd_eval(self, author, server, message, channel, mentions, code): """ Usage: {command_prefix}eval "evaluation string" runs a command thru the eval param for testing """ if author.id == self.config.master_id: result = None try: result = eval(code) except Exception: formatted_lines = traceback.format_exc().splitlines() return Response('```py\n{}\n{}\n```'.format(formatted_lines[-1], '/n'.join(formatted_lines[4:-1])), reply=True) if asyncio.iscoroutine(result): result = await result if result: return Response('```{}```'.format(result), reply=True) return Response(':thumbsup:'.format(result), reply=True) return
def isawaitable(obj): ''' Return True if the object is an awaitable or is a function that returns an awaitable. This function is used internally by aiotesting. ''' if PY35: result = inspect.iscoroutinefunction(obj) or inspect.isawaitable(obj) elif PY34: result = (isinstance(obj, asyncio.Future) or asyncio.iscoroutine(obj) or hasattr(obj, '__await__')) else: raise Exception( 'isawaitable is not supported on Python {}'.format( sys.version_info)) return result
def __setattr__(self, attr, val): if attr.startswith('_'): super().__setattr__(attr, val) else: if isinstance(val, list): self._dct[attr] = ListProxy(val) elif isinstance(val, dict): self._dct[attr] = DictProxy(val) elif asyncio.iscoroutine(val) or asyncio.iscoroutinefunction(val) or isinstance(val, asyncio.Future): val = asyncio.async(val) def set_later(future_val, attr=attr): setattr(self, attr, future_val.result()) val.add_done_callback(set_later) else: self._dct[attr] = val
def _format_coroutine(coro): if asyncio.iscoroutine(coro) \ and not hasattr(coro, 'cr_code') \ and not hasattr(coro, 'gi_code'): # Most likely a Cython coroutine coro_name = '{}()'.format(coro.__qualname__ or coro.__name__) running = False try: running = coro.cr_running except AttributeError: try: running = coro.gi_running except AttributeError: pass if running: return '{} running'.format(coro_name) else: return coro_name return _old_format_coroutine(coro)
def wait_on_tx_confirmation(self, tx_hash, interval_check_callback=None, check_db=False): while True: resp = await self.fetch("/tx/{}".format(tx_hash)) self.assertEqual(resp.code, 200) body = json_decode(resp.body) if body is None or body['blockNumber'] is None: if interval_check_callback: f = interval_check_callback() if asyncio.iscoroutine(f): await f await asyncio.sleep(1) else: if check_db: while True: async with self.pool.acquire() as con: row = await con.fetchrow("SELECT * FROM transactions WHERE hash = $1 AND status = 'confirmed'", tx_hash) if row: break return body
def test_alru_cache_deco(loop, check_lru): asyncio.set_event_loop(loop) @alru_cache async def coro(): pass assert asyncio.iscoroutinefunction(coro) for attr in alru_cache_attrs: assert hasattr(coro, attr) for attr in alru_cache_calable_attrs: assert callable(getattr(coro, attr)) assert isinstance(coro._cache, dict) assert isinstance(coro.tasks, set) check_lru(coro, hits=0, misses=0, cache=0, tasks=0) assert asyncio.iscoroutine(coro())
def test_alru_cache_deco_called(check_lru, loop): asyncio.set_event_loop(loop) @alru_cache() async def coro(): pass assert asyncio.iscoroutinefunction(coro) for attr in alru_cache_attrs: assert hasattr(coro, attr) for attr in alru_cache_calable_attrs: assert callable(getattr(coro, attr)) assert isinstance(coro._cache, dict) assert isinstance(coro.tasks, set) check_lru(coro, hits=0, misses=0, cache=0, tasks=0) assert asyncio.iscoroutine(coro())
def test_alru_cache_fn_called(check_lru, loop): asyncio.set_event_loop(loop) async def coro(): pass coro_wrapped = alru_cache(coro) assert asyncio.iscoroutinefunction(coro_wrapped) for attr in alru_cache_attrs: assert hasattr(coro_wrapped, attr) for attr in alru_cache_calable_attrs: assert callable(getattr(coro_wrapped, attr)) assert isinstance(coro_wrapped._cache, dict) assert isinstance(coro_wrapped.tasks, set) check_lru(coro_wrapped, hits=0, misses=0, cache=0, tasks=0) assert asyncio.iscoroutine(coro_wrapped())
def init(self): fields = ((name, field) for name, field in self._fields if self._request.method in field.methods) data = self._data manager_dict = self.manager_dict for name, field in fields: field.name = name if name in data: val = field._get_value(data[name]) elif field.required is False: val = field.default() else: raise abort(status=406, text='Field {} required'.format(name)) if asyncio.iscoroutine(val): manager_dict[name] = yield from val else: manager_dict[name] = val
def __asy_go(seed, *fns): if _.is_func(seed): seed = await seed() if _.is_asy(seed) else seed() if asyncio.iscoroutine(seed): seed = await seed for fn in fns: if fn is __: seed = __ elif asyncio.iscoroutinefunction(fn): seed = await fn(*seed['value']) if _.is_mr(seed) else await fn(seed) else: seed = fn(*seed['value']) if _.is_mr(seed) else fn() if seed is __ else fn(seed) if asyncio.iscoroutine(seed): seed = await seed return seed
def on_applied(self, srcid, lcid, result, lcodec): if iscoroutine(result): # A method may be a coroutine ... result = self.loop.create_task(result) if isinstance(result, Future): # ... or it may return a Future ... if lcid is not None: if self.lcalls.pop(lcid, None): # cancel was already requested result.cancel() else: self.lcalls[lcid] = result result.add_done_callback(partial(self.on_done, srcid, lcid, lcodec)) else: # ... or it may return a simple value. self.lcalls.pop(lcid, None) self.on_result(srcid, lcid, result, lcodec)
def _async_add_job(self, target: Callable[..., None], *args: Any) -> None: """Add a job from within the eventloop. This method must be run in the event loop. target: target to call. args: parameters for method to call. """ if asyncio.iscoroutine(target): self.loop.create_task(target) elif is_callback(target): self.loop.call_soon(target, *args) elif asyncio.iscoroutinefunction(target): self.loop.create_task(target(*args)) else: self.loop.run_in_executor(None, target, *args)
def _async_add_job_tracking(self, target: Callable[..., None], *args: Any) -> None: """Add a job from within the eventloop. This method must be run in the event loop. target: target to call. args: parameters for method to call. """ task = None if asyncio.iscoroutine(target): task = self.loop.create_task(target) elif is_callback(target): self.loop.call_soon(target, *args) elif asyncio.iscoroutinefunction(target): task = self.loop.create_task(target(*args)) else: task = self.loop.run_in_executor(None, target, *args) # if a task is sheduled if task is not None: self._pending_tasks.append(task)
def extract_info(self, loop, *args, on_error=None, retry_on_error=False, **kwargs): """ Runs ytdl.extract_info within the threadpool. Returns a future that will fire when it's done. If `on_error` is passed and an exception is raised, the exception will be caught and passed to on_error as an argument. """ if callable(on_error): try: return await loop.run_in_executor(self.thread_pool, functools.partial(self.unsafe_ytdl.extract_info, *args, **kwargs)) except Exception as e: # (youtube_dl.utils.ExtractorError, youtube_dl.utils.DownloadError) # I hope I don't have to deal with ContentTooShortError's if asyncio.iscoroutinefunction(on_error): asyncio.ensure_future(on_error(e), loop=loop) elif asyncio.iscoroutine(on_error): asyncio.ensure_future(on_error, loop=loop) else: loop.call_soon_threadsafe(on_error, e) if retry_on_error: return await self.safe_extract_info(loop, *args, **kwargs) else: return await loop.run_in_executor(self.thread_pool, functools.partial(self.unsafe_ytdl.extract_info, *args, **kwargs))
def _get_subscribe_decorator(func): @wraps(func) def wrapper(*args, **kwargs): coroutine_func = func if not iscoroutine(func): coroutine_func = coroutine(func) return (async(coroutine_func(*args, **kwargs))) return wrapper
def log(fn=None, logger=logging.getLogger(), debug_level=logging.DEBUG): """ logs parameters and result - takes no arguments """ if fn is None: return partial(log, logger=logger, debug_level=debug_level) @wraps(fn) def func(*args, **kwargs): arg_string = "" for i in range(0, len(args)): var_name = fn.__code__.co_varnames[i] if var_name not in ['self', 'cls']: arg_string += var_name + ":" + str(args[i]) + "," arg_string = arg_string[0:len(arg_string) - 1] string = (RED + BOLD + '>> ' + END + 'Calling {0}({1})'.format(fn.__name__, arg_string)) if len(kwargs): string = ( RED + BOLD + '>> ' + END + 'Calling {0} with args {1} and kwargs {2}'.format(fn.__name__, arg_string, kwargs)) logger.log(debug_level, string) wrapped_fn = fn if not asyncio.iscoroutine(fn): wrapped_fn = asyncio.coroutine(fn) try: result = yield from wrapped_fn(*args, **kwargs) string = BLUE + BOLD + '<< ' + END + 'Return {0} with result :{1}'.format(fn.__name__, result) logger.log(debug_level, string) return result except Exception as e: string = (RED + BOLD + '>> ' + END + '{0} raised exception :{1}'.format(fn.__name__, str(e))) logger.log(debug_level, string) raise e return func
def logx(supress_args=[], supress_all_args=False, supress_result=False, logger=logging.getLogger(), debug_level=logging.DEBUG): """ logs parameters and result takes arguments supress_args - list of parameter names to supress supress_all_args - boolean to supress all arguments supress_result - boolean to supress result receiver - custom logging function which takes a string as input; defaults to logging on stdout """ def decorator(fn): def func(*args, **kwargs): if not supress_all_args: arg_string = "" for i in range(0, len(args)): var_name = fn.__code__.co_varnames[i] if var_name != "self" and var_name not in supress_args: arg_string += var_name + ":" + str(args[i]) + "," arg_string = arg_string[0:len(arg_string) - 1] string = (RED + BOLD + '>> ' + END + 'Calling {0}({1})'.format(fn.__name__, arg_string)) if len(kwargs): string = ( RED + BOLD + '>> ' + END + 'Calling {0} with args {1} and kwargs {2}'.format( fn.__name__, arg_string, kwargs)) logger.log(debug_level, string) wrapped_fn = fn if not asyncio.iscoroutine(fn): wrapped_fn = asyncio.coroutine(fn) result = yield from wrapped_fn(*args, **kwargs) if not supress_result: string = BLUE + BOLD + '<< ' + END + 'Return {0} with result : {1}'.format(fn.__name__, result) logger.log(debug_level, string) return result return func return decorator
def evaluate(self, ctx, *, code): """Evaluates code. Modified function, originally made by Rapptz""" # [p]eval <code> code = code.strip('` ') result = None global_vars = globals().copy() global_vars['bot'] = self.bot global_vars['ctx'] = ctx global_vars['message'] = ctx.message global_vars['author'] = ctx.message.author global_vars['channel'] = ctx.message.channel global_vars['server'] = ctx.message.server try: result = eval(code, global_vars, locals()) except Exception as e: await self.bot.say(f.block(type(e).__name__ + ': ' + str(e), 'py')) return if asyncio.iscoroutine(result): result = await result result = f.block(result, 'py') await self.bot.say(result)
def do(self, coroutine): if asyncio.iscoroutine(coroutine): return self.loop.run_until_complete(coroutine) return False
def get(self, key): if self.is_request_signed(): address = self.verify_request() self.set_login_result(key, address) self.set_status(204) else: if key not in self.login_requests: self.create_new_login_future(key) address = await self.login_requests[key] if address is None: raise JSONHTTPError(400, body={'errors': [{'id': 'request_timeout', 'message': 'Login request timed out'}]}) if address is False: raise JSONHTTPError(401, body={'errors': [{'id': 'login_failed', 'message': 'Login failed'}]}) if hasattr(self, 'on_login'): f = self.on_login(address) if asyncio.iscoroutine(f): f = await f return f # else self.write({"address": address})
def on_subscribed(self): def decorator(coro): assert aio.iscoroutine(coro), 'function should be coroutine' self._events_callbacks[EventType.SUBSCRIBED] = coro return coro return decorator
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')
def debug(self, ctx, *, code: str): """Evaluates code.""" code = code.strip('` ') python = '```py\n{}\n```' try: result = eval(code) except Exception as e: await self.bot.say(python.format(type(e).__name__ + ': ' + str(e))) return if asyncio.iscoroutine(result): result = await result await self.bot.say(python.format(result))
def debug2(self, ctx, *, code: str): """Runs code.""" code = code.strip('` ') python = '```py\n{}\n```' try: result = exec(code) except Exception as e: await self.bot.say(python.format(type(e).__name__ + ': ' + str(e))) return if asyncio.iscoroutine(result): result = await result await self.bot.say(python.format(result))
def execute(coro): """ run a function or coroutine Parameters ---------- coro : asyncio.coroutine or function """ if asyncio.iscoroutine(coro): return await coro else: return coro
def debug(ctx, *, code): """Evaluates code Modified function, originally made by Rapptz""" if ctx.message.author.id == userinfo["id"]: print("found owner") code = code.strip('` ') python = '```py\n{}\n```' result = None global_vars = globals().copy() global_vars['bot'] = bot global_vars['ctx'] = ctx global_vars['message'] = ctx.message global_vars['author'] = ctx.message.author global_vars['channel'] = ctx.message.channel global_vars['server'] = ctx.message.server try: result = eval(code, global_vars, locals()) except Exception as e: await bot.edit_message(ctx.message, python.format(type(e).__name__ + ': ' + str(e))) return if asyncio.iscoroutine(result): result = await result result = python.format(result) await bot.edit_message(ctx.message, result)
def setup_coro(func): @functools.wraps(func) async def setup_coro_wrapper(*args, **kwargs): logger.info(f'{func.__name__} started!') try: if asyncio.iscoroutine(func): await func else: await func(*args, **kwargs) except asyncio.CancelledError: logger.info(f'{func.__name__} stopped!') return setup_coro_wrapper
def _async(future, loop): # trollius iscoroutine() accepts trollius and asyncio coroutine # objects if trollius.iscoroutine(future): return _create_task(future, loop) else: return future
def _async(future, loop): if asyncio.iscoroutine(future): return _create_task(future, loop) else: return future
def __init__(self, coroutine): assert asyncio.iscoroutine(coroutine) self.coroutine = coroutine
def asyncio_perform(dispatcher, effect): if isinstance(effect, AsyncFunc): return await effect.coroutine intent = effect.intent if isinstance(intent, ChainedIntent): try: sub_effect = next(intent.generator) while True: assert isinstance(sub_effect, (Effect, AsyncFunc)), ( '`ChainedIntent` generator must only yield `Effect` or ' '`AsyncFunc` objects (got %s)' % sub_effect) try: if isinstance(sub_effect, AsyncFunc): ret = await sub_effect.coroutine else: ret = await asyncio_perform(dispatcher, sub_effect) except Exception as exc: sub_effect = intent.generator.throw(exc) else: sub_effect = intent.generator.send(ret) except StopIteration as exc: return exc.value else: performer = dispatcher(intent) ret = performer(intent) if asyncio.iscoroutine(ret): ret = await ret if isinstance(ret, Effect): return await asyncio_perform(dispatcher, ret) elif isinstance(ret, AsyncFunc): return await ret.coroutine else: return ret
def run_coro(coro, session): if not asyncio.iscoroutine(coro): coro = _convert_future_to_coro(coro) if session.loop.is_running(): return asyncio.run_coroutine_threadsafe(coro, session.loop).result() else: return session.loop.run_until_complete(coro)
def get_value(self, field, obj, value): if value is None: return None try: value = get_adapter(field, IJSONToValue, args=[value, obj]) if asyncio.iscoroutine(value): value = await value field.validate(value) return value except ComponentLookupError: raise ValueDeserializationError( field, value, 'Deserializer not found for field')
def apply_coroutine(func: types.FunctionType, *args, **kwargs) -> object: """ Call a function with the supplied arguments. If the result is a coroutine, await it. """ result = func(*args, **kwargs) if asyncio.iscoroutine(result): return await result return result
def execute_futures(self): ''' Should *not* be a coroutine since the deleting of the request object causes this to be canceled otherwise. ''' if self._futures is None: return futures = [] for fut in self._futures.values(): if not asyncio.iscoroutine(fut): fut = fut() futures.append(fut) task = asyncio.ensure_future(asyncio.gather(*futures)) self._futures = {} return task
def start_asyncio_task(function, *args, **kwargs): """start an async callable and track its execution Args: function: callable, async coroutine or coroutine_function args: tuple, positional arguments for the function kwargs: dict, keyword arguments for the function Returns: asyncio.Task instance for the execution of the function Raises: RuntimeError: the function is not a coroutine or coroutine_function """ loop = asyncio.get_event_loop() if asyncio.iscoroutinefunction(function): task = asyncio.ensure_future(function(tracking.bot, *args, **kwargs), loop=loop) elif asyncio.iscoroutine(function): task = asyncio.ensure_future(function, loop=loop) else: raise RuntimeError("coroutine function must be supplied") tracking.register_asyncio_task(task) logger.debug(task) return task
def get_prefix(self, msg): prefixes = self.bot.command_prefix if callable(prefixes): prefixes = prefixes(self.bot, msg) if asyncio.iscoroutine(prefixes): prefixes = await prefixes for p in prefixes: if msg.content.startswith(p): return p return None
def call(response): if asyncio.iscoroutine(response): return (yield from response) else: return response