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