Python asyncio.AbstractEventLoop() Examples

The following are 30 code examples of asyncio.AbstractEventLoop(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module asyncio , or try the search function .
Example #1
Source File: app.py    From quart with MIT License 7 votes vote down vote up
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,
                }
            ) 
Example #2
Source File: _input.py    From pyuavcan with MIT License 6 votes vote down vote up
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() 
Example #3
Source File: _subscriber.py    From pyuavcan with MIT License 6 votes vote down vote up
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  ---------------------------------------- 
Example #4
Source File: base_client.py    From python-slackclient with MIT License 6 votes vote down vote up
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 
Example #5
Source File: server.py    From backend.ai-manager with GNU Lesser General Public License v3.0 6 votes vote down vote up
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)) 
Example #6
Source File: connection.py    From aioapns with Apache License 2.0 6 votes vote down vote up
def __init__(self,
                 topic: Optional[str] = None,
                 max_connections: int = 10,
                 max_connection_attempts: Optional[int] = None,
                 loop: Optional[asyncio.AbstractEventLoop] = None,
                 use_sandbox: bool = False):

        self.apns_topic = topic
        self.max_connections = max_connections
        if use_sandbox:
            self.protocol_class = APNsDevelopmentClientProtocol
        else:
            self.protocol_class = APNsProductionClientProtocol

        self.loop = loop or asyncio.get_event_loop()
        self.connections = []
        self._lock = asyncio.Lock(loop=self.loop)
        self.max_connection_attempts = max_connection_attempts 
Example #7
Source File: _server.py    From pyuavcan with MIT License 6 votes vote down vote up
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  ---------------------------------------- 
Example #8
Source File: connection.py    From aioapns with Apache License 2.0 6 votes vote down vote up
def __init__(self,
                 key_file: str,
                 key_id: str,
                 team_id: str,
                 topic: str,
                 max_connections: int = 10,
                 max_connection_attempts: Optional[int] = None,
                 loop: Optional[asyncio.AbstractEventLoop] = None,
                 use_sandbox: bool = False):

        super(APNsKeyConnectionPool, self).__init__(
            topic=topic,
            max_connections=max_connections,
            max_connection_attempts=max_connection_attempts,
            loop=loop,
            use_sandbox=use_sandbox,
        )

        self.key_id = key_id
        self.team_id = team_id

        with open(key_file) as f:
            self.key = f.read() 
Example #9
Source File: _input.py    From pyuavcan with MIT License 6 votes vote down vote up
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) 
Example #10
Source File: server.py    From maubot with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, management_api: web.Application, config: Config,
                 loop: asyncio.AbstractEventLoop) -> None:
        self.loop = loop or asyncio.get_event_loop()
        self.app = web.Application(loop=self.loop, client_max_size=100 * 1024 * 1024)
        self.config = config

        self.setup_appservice()
        self.app.add_subapp(config["server.base_path"], management_api)
        self.setup_instance_subapps()
        self.setup_management_ui()

        self.runner = web.AppRunner(self.app, access_log_class=AccessLogger) 
Example #11
Source File: api.py    From bot with MIT License 6 votes vote down vote up
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() 
Example #12
Source File: service.py    From pyquarkchain with MIT License 6 votes vote down vote up
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) 
Example #13
Source File: telegrambaseclient.py    From Telethon with MIT License 6 votes vote down vote up
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 
Example #14
Source File: __init__.py    From trader with Apache License 2.0 6 votes vote down vote up
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 
Example #15
Source File: task.py    From saltyrtc-server-python with MIT License 5 votes vote down vote up
def __init__(
            self,
            log: Logger,
            loop: asyncio.AbstractEventLoop
    ) -> None:
        self._log = log
        self._loop = loop
        self._state = JobQueueState.open  # type: JobQueueState
        self._queue = \
            asyncio.Queue(loop=self._loop)  # type: asyncio.Queue[Union[Job, FinalJob]]

        # Job runner
        self._runner = None  # type: Optional[asyncio.Task[None]]
        self._active_job = None  # type: Optional[Job] 
Example #16
Source File: _media.py    From pyuavcan with MIT License 5 votes vote down vote up
def loop(self) -> asyncio.AbstractEventLoop:
        return asyncio.get_event_loop() 
Example #17
Source File: server.py    From saltyrtc-server-python with MIT License 5 votes vote down vote up
def __init__(
            self,
            keys: Optional[Sequence[ServerSecretPermanentKey]],
            paths: Paths,
            loop: Optional[asyncio.AbstractEventLoop] = None,
    ) -> None:
        self._log = util.get_logger('server')
        self._loop = asyncio.get_event_loop() if loop is None else loop

        # Protocol class
        self.protocol_class = ServerProtocol  # type: Type[ServerProtocol]

        # WebSocket server instance
        self._server = None  # type: Optional[websockets.server.WebSocketServer]

        # Validate & store keys
        if keys is None:
            keys = []
        if len(keys) != len({key.pk for key in keys}):
            raise ServerKeyError('Repeated permanent keys')
        self.keys = OrderedDict(
            ((ServerPublicPermanentKey(key.pk), key) for key in keys))  # type: Keys

        # Store paths
        self.paths = paths

        # Store server protocols and closing task
        self.protocols = set()  # type: Set[ServerProtocol]
        self._close_task = None  # type: Optional[asyncio.Task[None]]

        # Event Registry
        self._events = EventRegistry() 
Example #18
Source File: task.py    From saltyrtc-server-python with MIT License 5 votes vote down vote up
def __init__(
            self,
            log: Logger,
            loop: asyncio.AbstractEventLoop,
    ) -> None:
        self._log = log
        self._loop = loop
        self._cancelled = False
        self._have_result = False
        self._result_future = \
            asyncio.Future(loop=self._loop)  # type: asyncio.Future[Result]
        self._tasks = None  # type: Optional[Set[asyncio.Task[None]]]
        self._tasks_remaining = 0 
Example #19
Source File: _loopback.py    From pyuavcan with MIT License 5 votes vote down vote up
def loop(self) -> asyncio.AbstractEventLoop:
        return self._loop 
Example #20
Source File: _loopback.py    From pyuavcan with MIT License 5 votes vote down vote up
def __init__(self,
                 local_node_id: typing.Optional[int],
                 loop:          typing.Optional[asyncio.AbstractEventLoop] = None):
        self._loop = loop if loop is not None else asyncio.get_event_loop()
        self._local_node_id = int(local_node_id) if local_node_id is not None else None
        self._input_sessions: typing.Dict[pyuavcan.transport.InputSessionSpecifier, LoopbackInputSession] = {}
        self._output_sessions: typing.Dict[pyuavcan.transport.OutputSessionSpecifier, LoopbackOutputSession] = {}
        # Unlimited protocol capabilities by default.
        self._protocol_parameters = pyuavcan.transport.ProtocolParameters(
            transfer_id_modulo=2 ** 64,
            max_nodes=2 ** 64,
            mtu=2 ** 64 - 1,
        ) 
Example #21
Source File: _socketcan.py    From pyuavcan with MIT License 5 votes vote down vote up
def __init__(self, iface_name: str, mtu: int, loop: typing.Optional[asyncio.AbstractEventLoop] = None) -> None:
        """
        CAN Classic/FD is selected automatically based on the MTU. It is not possible to use CAN FD with MTU of 8 bytes.

        :param iface_name: E.g., ``can0``.

        :param mtu: The maximum data field size in bytes. CAN FD is used if this value > 8, Classic CAN otherwise.
            This value must belong to Media.VALID_MTU_SET.

        :param loop: The event loop to use. Defaults to :func:`asyncio.get_event_loop`.
        """
        self._mtu = int(mtu)
        if self._mtu not in self.VALID_MTU_SET:
            raise ValueError(f'Invalid MTU: {self._mtu} not in {self.VALID_MTU_SET}')

        self._iface_name = str(iface_name)
        self._loop = loop if loop is not None else asyncio.get_event_loop()

        self._is_fd = self._mtu > _NativeFrameDataCapacity.CAN_CLASSIC
        self._native_frame_data_capacity = int({
            False: _NativeFrameDataCapacity.CAN_CLASSIC,
            True:  _NativeFrameDataCapacity.CAN_FD,
        }[self._is_fd])
        self._native_frame_size = _FRAME_HEADER_STRUCT.size + self._native_frame_data_capacity

        self._sock = _make_socket(iface_name, can_fd=self._is_fd)
        self._closed = False
        self._maybe_thread: typing.Optional[threading.Thread] = None
        self._loopback_enabled = False

        self._ancillary_data_buffer_size = socket.CMSG_SPACE(_TIMEVAL_STRUCT.size)  # Used for recvmsg()

        super(SocketCANMedia, self).__init__() 
Example #22
Source File: _input_session.py    From pyuavcan with MIT License 5 votes vote down vote up
def __init__(self,
                 specifier:        pyuavcan.transport.InputSessionSpecifier,
                 payload_metadata: pyuavcan.transport.PayloadMetadata,
                 loop:             asyncio.AbstractEventLoop,
                 closer:           typing.Callable[[], None]):
        self._specifier = specifier
        self._payload_metadata = payload_metadata
        self._loop = loop
        self._closer = closer
        self._transfer_id_timeout = float(self.DEFAULT_TRANSFER_ID_TIMEOUT)
        self._stats = pyuavcan.transport.SessionStatistics()
        self._queue: asyncio.Queue[pyuavcan.transport.TransferFrom] = asyncio.Queue(loop=loop)
        super(LoopbackInputSession, self).__init__() 
Example #23
Source File: _output_session.py    From pyuavcan with MIT License 5 votes vote down vote up
def __init__(self,
                 specifier:        pyuavcan.transport.OutputSessionSpecifier,
                 payload_metadata: pyuavcan.transport.PayloadMetadata,
                 loop:             asyncio.AbstractEventLoop,
                 closer:           typing.Callable[[], None],
                 router:           TransferRouter):
        self._specifier = specifier
        self._payload_metadata = payload_metadata
        self._loop = loop
        self._closer = closer
        self._router = router
        self._stats = pyuavcan.transport.SessionStatistics()
        self._feedback_handler: typing.Optional[typing.Callable[[pyuavcan.transport.Feedback], None]] = None
        self._injected_exception: typing.Optional[Exception] = None
        self._should_timeout = False 
Example #24
Source File: _input.py    From pyuavcan with MIT License 5 votes vote down vote up
def __init__(self,
                 specifier:           pyuavcan.transport.InputSessionSpecifier,
                 payload_metadata:    pyuavcan.transport.PayloadMetadata,
                 tid_modulo_provider: typing.Callable[[], typing.Optional[int]],
                 loop:                asyncio.AbstractEventLoop,
                 finalizer:           typing.Callable[[], None]):
        """
        Do not call this directly! Use the factory method instead.
        """
        self._specifier = specifier
        self._payload_metadata = payload_metadata
        self._get_tid_modulo = tid_modulo_provider
        self._loop = loop
        self._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._get_tid_modulo(), (type(None), int))
        assert isinstance(self._loop, asyncio.AbstractEventLoop)
        assert callable(self._finalizer)

        self._inferiors: typing.List[pyuavcan.transport.InputSession] = []
        self._lock = asyncio.Lock(loop=self._loop)
        self._maybe_deduplicator: typing.Optional[Deduplicator] = None
        self._backlog: typing.List[RedundantTransferFrom] = []

        self._stat_transfers = 0
        self._stat_payload_bytes = 0
        self._stat_errors = 0 
Example #25
Source File: _redundant_transport.py    From pyuavcan with MIT License 5 votes vote down vote up
def loop(self) -> asyncio.AbstractEventLoop:
        """
        All inferiors run on the same event loop, which is configured statically once when the redundant transport
        is instantiated.
        The loop cannot be reassigned after instantiation.
        """
        return self._loop 
Example #26
Source File: _redundant_transport.py    From pyuavcan with MIT License 5 votes vote down vote up
def __init__(self, loop: typing.Optional[asyncio.AbstractEventLoop] = None) -> None:
        """
        :param loop: All inferiors shall run on the same event loop,
            which is configured once here and cannot be changed after the instance is constructed.
            If not provided, defaults to :func:`asyncio.get_event_loop`.
        """
        self._cols: typing.List[pyuavcan.transport.Transport] = []
        self._rows: typing.Dict[pyuavcan.transport.SessionSpecifier, RedundantSession] = {}
        self._loop = loop if loop is not None else asyncio.get_event_loop()
        self._check_matrix_consistency() 
Example #27
Source File: _serial.py    From pyuavcan with MIT License 5 votes vote down vote up
def loop(self) -> asyncio.AbstractEventLoop:
        return self._loop 
Example #28
Source File: _media.py    From pyuavcan with MIT License 5 votes vote down vote up
def loop(self) -> asyncio.AbstractEventLoop:
        """
        The asyncio event loop used to operate the media instance.
        Shall be the same one as that of the parent transport.
        """
        raise NotImplementedError 
Example #29
Source File: _socketcan.py    From pyuavcan with MIT License 5 votes vote down vote up
def loop(self) -> asyncio.AbstractEventLoop:
        return self._loop 
Example #30
Source File: _input.py    From pyuavcan with MIT License 5 votes vote down vote up
def __init__(self,
                 specifier:        pyuavcan.transport.InputSessionSpecifier,
                 payload_metadata: pyuavcan.transport.PayloadMetadata,
                 loop:             asyncio.AbstractEventLoop,
                 finalizer:        typing.Callable[[], None]):
        """
        Do not call this directly, use the factory method instead.
        """
        self._statistics_impl = PromiscuousUDPInputSessionStatistics()
        self._reassemblers: typing.Dict[int, TransferReassembler] = {}
        super(PromiscuousUDPInputSession, self).__init__(specifier=specifier,
                                                         payload_metadata=payload_metadata,
                                                         loop=loop,
                                                         finalizer=finalizer)