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


Python asyncio.AbstractEventLoop方法代码示例

本文整理汇总了Python中asyncio.AbstractEventLoop方法的典型用法代码示例。如果您正苦于以下问题:Python asyncio.AbstractEventLoop方法的具体用法?Python asyncio.AbstractEventLoop怎么用?Python asyncio.AbstractEventLoop使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在asyncio的用法示例。


在下文中一共展示了asyncio.AbstractEventLoop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _cancel_all_tasks

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import AbstractEventLoop [as 别名]
def _cancel_all_tasks(loop: asyncio.AbstractEventLoop) -> None:
    tasks = [task for task in asyncio.all_tasks(loop) if not task.done()]
    if not tasks:
        return

    for task in tasks:
        task.cancel()
    loop.run_until_complete(asyncio.gather(*tasks, loop=loop, return_exceptions=True))

    for task in tasks:
        if not task.cancelled() and task.exception() is not None:
            loop.call_exception_handler(
                {
                    "message": "unhandled exception during shutdown",
                    "exception": task.exception(),
                    "task": task,
                }
            ) 
开发者ID:pgjones,项目名称:quart,代码行数:20,代码来源:app.py

示例2: __init__

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import AbstractEventLoop [as 别名]
def __init__(self, io_loop: asyncio.AbstractEventLoop = None):
        super().__init__()
        self.io_loop = io_loop or asyncio.get_event_loop()
        self.sub_client = self.io_loop.run_until_complete(
                aioredis.create_redis((config.get('REDIS', 'host', fallback='localhost'),
                                       config.getint('REDIS', 'port', fallback=6379)),
                                      db=config.getint('REDIS', 'db', fallback=1)))
        self.redis_client = redis.StrictRedis(
            host=config.get('REDIS', 'host', fallback='localhost'),
            db=config.getint('REDIS', 'db', fallback=1), decode_responses=True)
        self.initialized = False
        self.sub_tasks = list()
        self.sub_channels = list()
        self.channel_router = dict()
        self.crontab_router = defaultdict(dict)
        self.datetime = None
        self.time = None
        self.loop_time = None 
开发者ID:BigBrotherTrade,项目名称:trader,代码行数:20,代码来源:__init__.py

示例3: loop

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import AbstractEventLoop [as 别名]
def loop(self: 'TelegramClient') -> asyncio.AbstractEventLoop:
        """
        Property with the ``asyncio`` event loop used by this client.

        Example
            .. code-block:: python

                # Download media in the background
                task = client.loop.create_task(message.download_media())

                # Do some work
                ...

                # Join the task (wait for it to complete)
                await task
        """
        return self._loop 
开发者ID:LonamiWebs,项目名称:Telethon,代码行数:19,代码来源:telegrambaseclient.py

示例4: __init__

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import AbstractEventLoop [as 别名]
def __init__(self, loop: asyncio.AbstractEventLoop, **kwargs):
        auth_headers = {
            'Authorization': f"Token {Keys.site_api}"
        }

        if 'headers' in kwargs:
            kwargs['headers'].update(auth_headers)
        else:
            kwargs['headers'] = auth_headers

        self.session = None
        self.loop = loop

        self._ready = asyncio.Event(loop=loop)
        self._creation_task = None
        self._default_session_kwargs = kwargs

        self.recreate() 
开发者ID:python-discord,项目名称:bot,代码行数:20,代码来源:api.py

示例5: handle_loop_error

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import AbstractEventLoop [as 别名]
def handle_loop_error(
    root_app: web.Application,
    loop: asyncio.AbstractEventLoop,
    context: Mapping[str, Any],
) -> None:
    if isinstance(loop, aiojobs.Scheduler):
        loop = current_loop()
    exception = context.get('exception')
    msg = context.get('message', '(empty message)')
    if exception is not None:
        if sys.exc_info()[0] is not None:
            log.exception('Error inside event loop: {0}', msg)
            if 'error_monitor' in root_app:
                loop.create_task(root_app['error_monitor'].capture_exception())
        else:
            exc_info = (type(exception), exception, exception.__traceback__)
            log.error('Error inside event loop: {0}', msg, exc_info=exc_info)
            if 'error_monitor' in root_app:
                loop.create_task(root_app['error_monitor'].capture_exception(exception)) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:21,代码来源:server.py

示例6: __init__

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import AbstractEventLoop [as 别名]
def __init__(
        self,
        token=None,
        base_url=BASE_URL,
        timeout=30,
        loop: Optional[asyncio.AbstractEventLoop] = None,
        ssl=None,
        proxy=None,
        run_async=False,
        use_sync_aiohttp=False,
        session=None,
        headers: Optional[dict] = None,
    ):
        self.token = None if token is None else token.strip()
        self.base_url = base_url
        self.timeout = timeout
        self.ssl = ssl
        self.proxy = proxy
        self.run_async = run_async
        self.use_sync_aiohttp = use_sync_aiohttp
        self.session = session
        self.headers = headers or {}
        self._logger = logging.getLogger(__name__)
        self._event_loop = loop 
开发者ID:slackapi,项目名称:python-slackclient,代码行数:26,代码来源:base_client.py

示例7: __init__

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import AbstractEventLoop [as 别名]
def __init__(
        self, token: CancelToken = None, loop: asyncio.AbstractEventLoop = None
    ) -> None:
        self.events = ServiceEvents()
        self._run_lock = asyncio.Lock()
        self._child_services = WeakSet()
        self._tasks = WeakSet()
        self._finished_callbacks = []

        self._loop = loop

        base_token = CancelToken(type(self).__name__, loop=loop)

        if token is None:
            self.cancel_token = base_token
        else:
            self.cancel_token = base_token.chain(token) 
开发者ID:QuarkChain,项目名称:pyquarkchain,代码行数:19,代码来源:service.py

示例8: __init__

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import AbstractEventLoop [as 别名]
def __init__(self,
                 impl:           SubscriberImpl[MessageClass],
                 loop:           asyncio.AbstractEventLoop,
                 queue_capacity: typing.Optional[int]):
        """
        Do not call this directly! Use :meth:`Presentation.make_subscriber`.
        """
        if queue_capacity is None:
            queue_capacity = 0      # This case is defined by the Queue API. Means unlimited.
        else:
            queue_capacity = int(queue_capacity)
            if queue_capacity < 1:
                raise ValueError(f'Invalid queue capacity: {queue_capacity}')

        self._closed = False
        self._impl = impl
        self._loop = loop
        self._maybe_task: typing.Optional[asyncio.Task[None]] = None
        self._rx: _Listener[MessageClass] = _Listener(asyncio.Queue(maxsize=queue_capacity, loop=loop))
        impl.add_listener(self._rx)

    # ----------------------------------------  HANDLER-BASED API  ---------------------------------------- 
开发者ID:UAVCAN,项目名称:pyuavcan,代码行数:24,代码来源:_subscriber.py

示例9: __init__

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import AbstractEventLoop [as 别名]
def __init__(self,
                 dtype:                            typing.Type[ServiceClass],
                 input_transport_session:          pyuavcan.transport.InputSession,
                 output_transport_session_factory: OutputTransportSessionFactory,
                 finalizer:                        TypedSessionFinalizer,
                 loop:                             asyncio.AbstractEventLoop):
        """
        Do not call this directly! Use :meth:`Presentation.get_server`.
        """
        self._dtype = dtype
        self._input_transport_session = input_transport_session
        self._output_transport_session_factory = output_transport_session_factory
        self._finalizer = finalizer
        self._loop = loop

        self._output_transport_sessions: typing.Dict[int, pyuavcan.transport.OutputSession] = {}
        self._maybe_task: typing.Optional[asyncio.Task[None]] = None
        self._closed = False
        self._send_timeout = DEFAULT_SERVICE_REQUEST_TIMEOUT

        self._served_request_count = 0
        self._deserialization_failure_count = 0
        self._malformed_request_count = 0

    # ----------------------------------------  MAIN API  ---------------------------------------- 
开发者ID:UAVCAN,项目名称:pyuavcan,代码行数:27,代码来源:_server.py

示例10: __init__

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import AbstractEventLoop [as 别名]
def __init__(self,
                 specifier:        pyuavcan.transport.InputSessionSpecifier,
                 payload_metadata: pyuavcan.transport.PayloadMetadata,
                 loop:             asyncio.AbstractEventLoop,
                 finalizer:        typing.Callable[[], None]):
        self._specifier = specifier
        self._payload_metadata = payload_metadata
        self._loop = loop
        self._maybe_finalizer: typing.Optional[typing.Callable[[], None]] = finalizer
        assert isinstance(self._specifier, pyuavcan.transport.InputSessionSpecifier)
        assert isinstance(self._payload_metadata, pyuavcan.transport.PayloadMetadata)
        assert isinstance(self._loop, asyncio.AbstractEventLoop)
        assert callable(self._maybe_finalizer)

        self._transfer_id_timeout = self.DEFAULT_TRANSFER_ID_TIMEOUT
        self._queue: asyncio.Queue[pyuavcan.transport.TransferFrom] = asyncio.Queue() 
开发者ID:UAVCAN,项目名称:pyuavcan,代码行数:18,代码来源:_input.py

示例11: __init__

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import AbstractEventLoop [as 别名]
def __init__(self,
                 specifier:        pyuavcan.transport.InputSessionSpecifier,
                 payload_metadata: pyuavcan.transport.PayloadMetadata,
                 loop:             asyncio.AbstractEventLoop,
                 finalizer:        typing.Callable[[], None]):
        """
        Do not call this directly.
        Instead, use the factory method :meth:`pyuavcan.transport.serial.SerialTransport.get_input_session`.
        """
        self._specifier = specifier
        self._payload_metadata = payload_metadata
        self._loop = loop
        assert self._loop is not None

        if not isinstance(self._specifier, pyuavcan.transport.InputSessionSpecifier) or \
                not isinstance(self._payload_metadata, pyuavcan.transport.PayloadMetadata):  # pragma: no cover
            raise TypeError('Invalid parameters')

        self._statistics = SerialInputSessionStatistics()
        self._transfer_id_timeout = self.DEFAULT_TRANSFER_ID_TIMEOUT
        self._queue: asyncio.Queue[pyuavcan.transport.TransferFrom] = asyncio.Queue()
        self._reassemblers: typing.Dict[int, TransferReassembler] = {}

        super(SerialInputSession, self).__init__(finalizer) 
开发者ID:UAVCAN,项目名称:pyuavcan,代码行数:26,代码来源:_input.py

示例12: __init__

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import AbstractEventLoop [as 别名]
def __init__(self,
                 apns_topic: str,
                 loop: Optional[asyncio.AbstractEventLoop] = None,
                 on_connection_lost: Optional[
                     Callable[['APNsBaseClientProtocol'], NoReturn]] = None,
                 auth_provider: Optional[AuthorizationHeaderProvider] = None):
        super(APNsBaseClientProtocol, self).__init__()
        self.apns_topic = apns_topic
        self.loop = loop or asyncio.get_event_loop()
        self.on_connection_lost = on_connection_lost
        self.auth_provider = auth_provider

        self.requests = {}
        self.request_streams = {}
        self.request_statuses = {}
        self.inactivity_timer = None 
开发者ID:Fatal1ty,项目名称:aioapns,代码行数:18,代码来源:connection.py

示例13: test_app_loop_running

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import AbstractEventLoop [as 别名]
def test_app_loop_running(app):
    @app.get("/test")
    async def handler(request):
        assert isinstance(app.loop, asyncio.AbstractEventLoop)
        return text("pass")

    request, response = app.test_client.get("/test")
    assert response.text == "pass" 
开发者ID:huge-success,项目名称:sanic,代码行数:10,代码来源:test_app.py

示例14: listen

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import AbstractEventLoop [as 别名]
def listen(self, *, loop: asyncio.AbstractEventLoop, config):
        self._loop = loop
        self._config = config
        if self._config['debug']:
            self.shutdown_grace_period = 0
            self.shutdown_wait_period = 0
            self._debug = True 
开发者ID:wasp,项目名称:waspy,代码行数:9,代码来源:httptransport.py

示例15: _get_mock_loop

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import AbstractEventLoop [as 别名]
def _get_mock_loop() -> unittest.mock.Mock:
    """Return a mocked asyncio.AbstractEventLoop."""
    loop = unittest.mock.create_autospec(spec=AbstractEventLoop, spec_set=True)

    # Since calling `create_task` on our MockBot does not actually schedule the coroutine object
    # as a task in the asyncio loop, this `side_effect` calls `close()` on the coroutine object
    # to prevent "has not been awaited"-warnings.
    loop.create_task.side_effect = lambda coroutine: coroutine.close()

    return loop 
开发者ID:python-discord,项目名称:bot,代码行数:12,代码来源:helpers.py


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