本文整理汇总了Python中asyncio.CancelledError方法的典型用法代码示例。如果您正苦于以下问题:Python asyncio.CancelledError方法的具体用法?Python asyncio.CancelledError怎么用?Python asyncio.CancelledError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类asyncio
的用法示例。
在下文中一共展示了asyncio.CancelledError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: patcher
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import CancelledError [as 别名]
def patcher(self):
await self.bot.wait_until_ready()
try:
await asyncio.sleep(6) # be safe lolz
while True:
if not hasattr(self.bot.send_message, 'old'):
print(
'[WARNING:] -- Overwriting bot.send_message with '
'send_lolz. If bot.send_message is not reloaded,')
print(
'[WARNING:] -- in the event of a crash of the lolz '
'cog, you may not be able revert to bot.send_message '
'without a restart/reloading lolz')
self.bot.send_message = self.send_lolz(self.bot.send_message)
await asyncio.sleep(1)
except asyncio.CancelledError:
pass
示例2: sse
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import CancelledError [as 别名]
def sse():
queue = asyncio.Queue()
app.clients.add(queue)
async def send_events():
while True:
try:
data = await queue.get()
event = ServerSentEvent(data)
yield event.encode()
except asyncio.CancelledError as error:
app.clients.remove(queue)
response = await make_response(
send_events(),
{
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Transfer-Encoding': 'chunked',
},
)
response.timeout = None
return response
示例3: test_app_handle_request_asyncio_cancelled_error
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import CancelledError [as 别名]
def test_app_handle_request_asyncio_cancelled_error() -> None:
app = Quart(__name__)
@app.route("/")
async def index() -> NoReturn:
raise asyncio.CancelledError()
request = app.request_class(
"GET",
"http",
"/",
b"",
Headers([("host", "quart.com")]),
"",
"1.1",
send_push_promise=no_op_push,
)
with pytest.raises(asyncio.CancelledError):
await app.handle_request(request)
示例4: test_middleware_response_raise_cancelled_error
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import CancelledError [as 别名]
def test_middleware_response_raise_cancelled_error(app, caplog):
app.config.RESPONSE_TIMEOUT = 1
@app.middleware("response")
async def process_response(request, response):
raise CancelledError("CancelledError at response middleware")
@app.get("/")
def handler(request):
return text("OK")
with caplog.at_level(logging.ERROR):
reqrequest, response = app.test_client.get("/")
assert response.status == 503
assert (
"sanic.root",
logging.ERROR,
"Exception occurred while handling uri: 'http://127.0.0.1:42101/'",
) not in caplog.record_tuples
示例5: start
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import CancelledError [as 别名]
def start(self, handler):
print(f"-- Listening for rabbitmq messages on queue {self.queue} --")
self._handler = handler
await self._channel_ready.wait()
# channel hasn't actually been bootstraped yet
await self._bootstrap_channel(self.channel)
try:
await self._done_future
except asyncio.CancelledError:
pass
# shutting down
logger.warning("Shutting down rabbitmq transport")
await self.channel.basic_cancel(self._consumer_tag)
await self.close()
while self._counter > 0:
await asyncio.sleep(1)
示例6: _send_loop
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import CancelledError [as 别名]
def _send_loop(self):
"""
This loop is constantly popping items off the queue to send them.
"""
try:
while self._connected:
self._send(await self._send_queue.get())
await self._writer.drain()
except asyncio.CancelledError:
pass
except Exception as e:
if isinstance(e, IOError):
self._log.info('The server closed the connection while sending')
else:
self._log.exception('Unexpected exception in the send loop')
await self.disconnect()
示例7: test_quit
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import CancelledError [as 别名]
def test_quit(redis):
expected = (ConnectionClosedError, ConnectionError)
try:
assert b'OK' == await redis.quit()
except expected:
pass
if not isinstance(redis.connection, ConnectionsPool):
# reader task may not yet been cancelled and _do_close not called
# so the ConnectionClosedError may be raised (or ConnectionError)
with pytest.raises(expected):
try:
await redis.ping()
except asyncio.CancelledError:
assert False, "Cancelled error must not be raised"
# wait one loop iteration until it get surely closed
await asyncio.sleep(0)
assert redis.connection.closed
with pytest.raises(ConnectionClosedError):
await redis.ping()
示例8: view_logs
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import CancelledError [as 别名]
def view_logs(server: str, token: str) -> None:
async with ClientSession() as session:
async with session.ws_connect(f"{server}/_matrix/maubot/v1/logs") as ws:
await ws.send_str(token)
try:
msg: WSMessage
async for msg in ws:
if msg.type == WSMsgType.TEXT:
if not handle_msg(msg.json()):
break
elif msg.type == WSMsgType.ERROR:
print(Fore.YELLOW + "Connection error: " + msg.data + Fore.RESET)
elif msg.type == WSMsgType.CLOSE:
print(Fore.YELLOW + "Server closed connection" + Fore.RESET)
except asyncio.CancelledError:
pass
示例9: run_async_coroutine
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import CancelledError [as 别名]
def run_async_coroutine(self, coroutine_to_run, timeout):
"""Start coroutine in dedicated thread and await its result with timeout"""
start_time = time.time()
coro_future = self.start_async_coroutine(coroutine_to_run)
# run_coroutine_threadsafe returns future as concurrent.futures.Future() and not asyncio.Future
# so, we can await it with timeout inside current thread
try:
coro_result = coro_future.result(timeout=timeout)
self.logger.debug("scheduled {} returned {}".format(coroutine_to_run, coro_result))
return coro_result
except concurrent.futures.TimeoutError:
passed = time.time() - start_time
raise MolerTimeout(timeout=timeout,
kind="run_async_coroutine({})".format(coroutine_to_run),
passed_time=passed)
except concurrent.futures.CancelledError:
raise
示例10: open
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import CancelledError [as 别名]
def open(self):
"""Open TCP connection."""
self._debug('connecting to {}'.format(self))
# If a task is canceled while it is waiting for another concurrent operation,
# the task is notified of its cancellation by having a CancelledError exception
# raised at the point where it is waiting
try:
self._stream_reader, self._stream_writer = await asyncio.open_connection(host=self.host, port=self.port)
# self._stream_reader, self._stream_writer = await asyncio.wait_for(asyncio.open_connection(host=self.host, port=self.port), timeout=10)
except asyncio.CancelledError as err:
self._debug("CancelledError while awaiting for open_connection({}), err: {}".format(self, err))
# TODO: stop child task of asyncio.open_connection
raise
else:
self.connection_lost = asyncio.Future() # delayed to be created in same loop as open()
asyncio.ensure_future(self.forward_connection_read_data())
self._debug('connection {} is open'.format(self))
示例11: simple_db_mutate_returning_item
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import CancelledError [as 别名]
def simple_db_mutate_returning_item(result_cls, context, mutation_query, *,
item_query, item_cls):
async with context['dbpool'].acquire() as conn, conn.begin():
try:
result = await conn.execute(mutation_query)
if result.rowcount > 0:
result = await conn.execute(item_query)
item = await result.first()
return result_cls(True, 'success', item_cls.from_row(item))
else:
return result_cls(False, 'no matching record', None)
except (pg.IntegrityError, sa.exc.IntegrityError) as e:
return result_cls(False, f'integrity error: {e}', None)
except (asyncio.CancelledError, asyncio.TimeoutError):
raise
except Exception as e:
return result_cls(False, f'unexpected error: {e}', None)
示例12: catch_unexpected
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import CancelledError [as 别名]
def catch_unexpected(log, reraise_cancellation: bool = True, raven=None):
def _wrap(func):
@functools.wraps(func)
async def _wrapped(*args, **kwargs):
try:
return await func(*args, **kwargs)
except asyncio.CancelledError:
if reraise_cancellation:
raise
except Exception:
if raven:
raven.captureException()
log.exception('unexpected error!')
raise
return _wrapped
return _wrap
示例13: check_agent_lost
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import CancelledError [as 别名]
def check_agent_lost(app, interval):
try:
now = datetime.now(tzutc())
timeout = timedelta(seconds=app['config']['manager']['heartbeat-timeout'])
async def _check_impl():
async for agent_id, prev in app['redis_live'].ihscan('last_seen'):
prev = datetime.fromtimestamp(float(prev), tzutc())
if now - prev > timeout:
await app['event_dispatcher'].produce_event(
'instance_terminated', ('agent-lost', ),
agent_id=agent_id)
await redis.execute_with_retries(lambda: _check_impl())
except asyncio.CancelledError:
pass
# NOTE: This event is ignored during the grace period.
示例14: shutdown
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import CancelledError [as 别名]
def shutdown(app: web.Application) -> None:
app['agent_lost_checker'].cancel()
await app['agent_lost_checker']
app['stats_task'].cancel()
await app['stats_task']
checked_tasks = ('kernel_agent_event_collector', 'kernel_ddtimer')
for tname in checked_tasks:
t = app.get(tname, None)
if t and not t.done():
t.cancel()
await t
for task in app['pending_waits']:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
示例15: upstream
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import CancelledError [as 别名]
def upstream(self):
try:
async for msg in self.down_conn:
if msg.type in (web.WSMsgType.TEXT, web.WSMsgType.binary):
await self.write(msg.data, msg.type)
if self.upstream_cb is not None:
await self.upstream_cb(msg.data)
elif msg.type == web.WSMsgType.PING:
if self.ping_cb is not None:
await self.ping_cb(msg.data)
elif msg.type == aiohttp.WSMsgType.ERROR:
log.error("ws connection closed with exception {}",
self.up_conn.exception())
break
elif msg.type == aiohttp.WSMsgType.CLOSE:
break
# here, client gracefully disconnected
except asyncio.CancelledError:
# here, client forcibly disconnected
raise
finally:
await self.close_downstream()