当前位置: 首页>>代码示例>>Python>>正文


Python asyncio.CancelledError方法代码示例

本文整理汇总了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 
开发者ID:irdumbs,项目名称:Dumb-Cogs,代码行数:19,代码来源:lolz.py

示例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 
开发者ID:pgjones,项目名称:quart,代码行数:24,代码来源:broadcast.py

示例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) 
开发者ID:pgjones,项目名称:quart,代码行数:21,代码来源:test_app.py

示例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 
开发者ID:huge-success,项目名称:sanic,代码行数:22,代码来源:test_middleware.py

示例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) 
开发者ID:wasp,项目名称:waspy,代码行数:22,代码来源:rabbitmqtransport.py

示例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() 
开发者ID:LonamiWebs,项目名称:Telethon,代码行数:19,代码来源:connection.py

示例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() 
开发者ID:aio-libs,项目名称:aioredis,代码行数:24,代码来源:connection_commands_test.py

示例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 
开发者ID:maubot,项目名称:maubot,代码行数:18,代码来源:logs.py

示例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 
开发者ID:nokia,项目名称:moler,代码行数:19,代码来源:asyncio_runner.py

示例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)) 
开发者ID:nokia,项目名称:moler,代码行数:19,代码来源:tcp.py

示例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) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:19,代码来源:base.py

示例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 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:22,代码来源:utils.py

示例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. 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:21,代码来源:session.py

示例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 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:21,代码来源:session.py

示例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() 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:24,代码来源:wsproxy.py


注:本文中的asyncio.CancelledError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。