當前位置: 首頁>>代碼示例>>Python>>正文


Python trio.Event方法代碼示例

本文整理匯總了Python中trio.Event方法的典型用法代碼示例。如果您正苦於以下問題:Python trio.Event方法的具體用法?Python trio.Event怎麽用?Python trio.Event使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在trio的用法示例。


在下文中一共展示了trio.Event方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: monitor_messages

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Event [as 別名]
def monitor_messages(user_fs, event_bus, task_status):
    wakeup = trio.Event()

    def _on_message_received(event, index):
        nonlocal wakeup
        wakeup.set()
        # Don't wait for the *actual* awakening to change the status to
        # avoid having a period of time when the awakening is scheduled but
        # not yet notified to task_status
        task_status.awake()

    with event_bus.connect_in_context((CoreEvent.BACKEND_MESSAGE_RECEIVED, _on_message_received)):
        try:
            await user_fs.process_last_messages()
            task_status.started()
            while True:
                task_status.idle()
                await wakeup.wait()
                wakeup = trio.Event()
                await freeze_messages_monitor_mockpoint()
                await user_fs.process_last_messages()

        except FSBackendOfflineError as exc:
            raise BackendNotAvailable from exc 
開發者ID:Scille,項目名稱:parsec-cloud,代碼行數:26,代碼來源:messages_monitor.py

示例2: __init__

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Event [as 別名]
def __init__(self, trio_token, fn, args, kwargs, qt_on_success, qt_on_error):
        self._trio_token = trio_token
        assert isinstance(qt_on_success, ThreadSafeQtSignal)
        assert qt_on_success.args_types in ((), (QtToTrioJob,))
        self._qt_on_success = qt_on_success
        assert isinstance(qt_on_error, ThreadSafeQtSignal)
        assert qt_on_error.args_types in ((), (QtToTrioJob,))
        self._qt_on_error = qt_on_error
        self._fn = fn
        self._args = args
        self._kwargs = kwargs
        self.cancel_scope = None
        self._started = trio.Event()
        self._done = threading.Event()
        self.status = None
        self.ret = None
        self.exc = None 
開發者ID:Scille,項目名稱:parsec-cloud,代碼行數:19,代碼來源:trio_thread.py

示例3: test_init_online_backend_late_reply

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Event [as 別名]
def test_init_online_backend_late_reply(
    server_factory, core_config, alice, event_bus, backend
):
    can_serve_client = trio.Event()

    async def _handle_client(stream):
        await can_serve_client.wait()
        return await backend.handle_client(stream)

    async with server_factory(_handle_client, alice.organization_addr):
        with trio.fail_after(1):
            async with logged_core_factory(
                config=core_config, device=alice, event_bus=event_bus
            ) as core:
                # We don't want for backend to reply finish core init
                with core.event_bus.listen() as spy:
                    can_serve_client.set()
                    # Now backend reply, monitor should send events accordingly
                    await spy.wait(
                        CoreEvent.BACKEND_CONNECTION_CHANGED,
                        kwargs={"status": BackendConnStatus.READY, "status_exc": None},
                    ) 
開發者ID:Scille,項目名稱:parsec-cloud,代碼行數:24,代碼來源:test_logged_core.py

示例4: test_init_offline_backend_late_reply

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Event [as 別名]
def test_init_offline_backend_late_reply(server_factory, core_config, alice, event_bus):
    can_serve_client = trio.Event()

    async def _handle_client(stream):
        await can_serve_client.wait()
        await stream.aclose()

    async with server_factory(_handle_client, alice.organization_addr):
        with trio.fail_after(1):
            async with logged_core_factory(
                config=core_config, device=alice, event_bus=event_bus
            ) as core:
                with core.event_bus.listen() as spy:
                    can_serve_client.set()
                    await spy.wait(
                        CoreEvent.BACKEND_CONNECTION_CHANGED,
                        kwargs={"status": BackendConnStatus.LOST, "status_exc": ANY},
                    ) 
開發者ID:Scille,項目名稱:parsec-cloud,代碼行數:20,代碼來源:test_logged_core.py

示例5: __init__

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Event [as 別名]
def __init__(self, db, crawl_manager):
        '''
        Constructor.

        :param starbelly.db.ScheduleDB db:
        :param starbelly.job.CrawlManager crawl_manager: A crawl manager, used
            for starting jobs when they are scheduled to begin.
        '''
        self._db = db
        self._crawl_manager = crawl_manager

        self._events = list()
        self._schedules = dict()
        self._recv_channel = crawl_manager.get_job_state_channel()
        self._event_added = trio.Event()
        self._nursery = None
        self._running_jobs = dict() 
開發者ID:HyperionGray,項目名稱:starbelly,代碼行數:19,代碼來源:schedule.py

示例6: __init__

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Event [as 別名]
def __init__(
        self,
        local_name: str,
        conn: ConnectionAPI,
        subscriptions_changed: ConditionAPI,
        new_msg_func: Callable[[Broadcast], Awaitable[Any]],
    ) -> None:
        super().__init__(local_name, conn, new_msg_func)

        self._notify_lock = trio.Lock()  # type: ignore

        self._received_response = trio.Condition()  # type: ignore
        self._received_subscription = trio.Condition()  # type: ignore

        self._running = trio.Event()  # type: ignore
        self._stopped = trio.Event()  # type: ignore

        self._received_subscription = subscriptions_changed

        self._subscriptions_initialized = trio.Event()  # type: ignore

        self._running = trio.Event()  # type: ignore
        self._stopped = trio.Event()  # type: ignore
        self._ready = trio.Event()  # type: ignore 
開發者ID:ethereum,項目名稱:lahja,代碼行數:26,代碼來源:endpoint.py

示例7: _monitor_subscription_changes

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Event [as 別名]
def _monitor_subscription_changes(self) -> None:
        while not self.is_stopped:
            # We wait for the event to change and then immediately replace it
            # with a new event.  This **must** occur before any additional
            # `await` calls to ensure that any *new* changes to the
            # subscriptions end up operating on the *new* event and will be
            # picked up in the next iteration of the loop.
            await self._subscriptions_changed.wait()
            self._subscriptions_changed = trio.Event()

            # make a copy so that the set doesn't change while we iterate
            # over it
            subscribed_events = self.get_subscribed_events()

            async with trio.open_nursery() as nursery:
                async with self._remote_connections_changed:
                    for remote in self._connections:
                        nursery.start_soon(
                            remote.notify_subscriptions_updated,
                            subscribed_events,
                            False,
                        )
            async with self._remote_subscriptions_changed:
                self._remote_subscriptions_changed.notify_all() 
開發者ID:ethereum,項目名稱:lahja,代碼行數:26,代碼來源:endpoint.py

示例8: test_trio_endpoint_wait_for

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Event [as 別名]
def test_trio_endpoint_wait_for(endpoint_pair):
    alice, bob = endpoint_pair

    # NOTE: this test is the inverse of the broadcast test
    event = EventTest("test")

    done = trio.Event()

    async def _do_wait_for():
        result = await alice.wait_for(EventTest)

        assert isinstance(result, EventTest)
        assert result.value == "test"
        done.set()

    async with trio.open_nursery() as nursery:
        nursery.start_soon(_do_wait_for)

        await bob.wait_until_endpoint_subscribed_to(alice.name, EventTest)

        await bob.broadcast(event)
        await done.wait() 
開發者ID:ethereum,項目名稱:lahja,代碼行數:24,代碼來源:test_trio_endpoint_wait_for.py

示例9: test_no_messages_after_local_close

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Event [as 別名]
def test_no_messages_after_local_close(nursery):
    '''
    If the local endpoint initiates closing, then pending messages are discarded
    and any attempt to read a message will raise ConnectionClosed.
    '''
    client_closed = trio.Event()

    async def handler(request):
        # The server sends some messages and then closes.
        server = await request.accept()
        async with server:
            await server.send_message('1')
            await server.send_message('2')
            await client_closed.wait()

    server = await nursery.start(
        partial(serve_websocket, handler, HOST, 0, ssl_context=None))

    async with open_websocket(HOST, server.port, '/', use_ssl=False) as client:
        pass
    with pytest.raises(ConnectionClosed):
        await client.get_message()
    client_closed.set() 
開發者ID:HyperionGray,項目名稱:trio-websocket,代碼行數:25,代碼來源:test_connection.py

示例10: _send

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Event [as 別名]
def _send(self, event):
        '''
        Send an to the remote WebSocket.

        The reader task and one or more writers might try to send messages at
        the same time, so this method uses an internal lock to serialize
        requests to send data.

        :param wsproto.events.Event event:
        '''
        data = self._wsproto.send(event)
        async with self._stream_lock:
            logger.debug('%s sending %d bytes', self, len(data))
            try:
                await self._stream.send_all(data)
            except (trio.BrokenResourceError, trio.ClosedResourceError):
                await self._abort_web_socket()
                raise ConnectionClosed(self._close_reason) from None 
開發者ID:HyperionGray,項目名稱:trio-websocket,代碼行數:20,代碼來源:_impl.py

示例11: test_ping_pong

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Event [as 別名]
def test_ping_pong(manually_driven_discovery_pair):
    alice, bob = manually_driven_discovery_pair
    # Collect all pongs received by alice in a list for later inspection.
    got_pong = trio.Event()
    received_pongs = []

    async def recv_pong(node, payload, hash_):
        received_pongs.append((node, payload))
        got_pong.set()

    alice.recv_pong_v4 = recv_pong

    token = await alice.send_ping_v4(bob.this_node)

    with trio.fail_after(1):
        await bob.consume_datagram()
        await alice.consume_datagram()
        await got_pong.wait()

    assert len(received_pongs) == 1
    node, payload = received_pongs[0]
    assert node.id == bob.this_node.id
    assert token == payload[1] 
開發者ID:ethereum,項目名稱:trinity,代碼行數:25,代碼來源:test_discovery.py

示例12: start_handshake_as_initiator

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Event [as 別名]
def start_handshake_as_initiator(self,
                                     local_enr: ENR,
                                     remote_enr: ENR,
                                     message: BaseMessage,
                                     ) -> None:
        if not self.is_pre_handshake:
            raise ValueError("Can only register handshake when its not started yet")

        self.handshake_participant = HandshakeInitiator(
            local_private_key=self.local_private_key,
            local_enr=local_enr,
            remote_enr=remote_enr,
            initial_message=message,
        )
        self.handshake_successful_event = trio.Event()
        self.manager.run_task(self.check_handshake_timeout, self.handshake_successful_event)

        if not self.is_during_handshake:
            raise Exception("Invariant: After a handshake is started, the handshake is in progress") 
開發者ID:ethereum,項目名稱:trinity,代碼行數:21,代碼來源:packer.py

示例13: start_handshake_as_recipient

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Event [as 別名]
def start_handshake_as_recipient(self,
                                     auth_tag: Nonce,
                                     local_enr: ENR,
                                     remote_enr: Optional[ENR],
                                     ) -> None:
        if not self.is_pre_handshake:
            raise ValueError("Can only register handshake when its not started yet")

        self.handshake_participant = HandshakeRecipient(
            local_private_key=self.local_private_key,
            local_enr=local_enr,
            remote_node_id=self.remote_node_id,
            remote_enr=remote_enr,
            initiating_packet_auth_tag=auth_tag,
        )
        self.handshake_successful_event = trio.Event()
        self.manager.run_task(self.check_handshake_timeout, self.handshake_successful_event)

        if not self.is_during_handshake:
            raise Exception("Invariant: After a handshake is started, the handshake is in progress") 
開發者ID:ethereum,項目名稱:trinity,代碼行數:22,代碼來源:packer.py

示例14: __init__

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Event [as 別名]
def __init__(self) -> None:
        self._event = trio.Event() 
開發者ID:pgjones,項目名稱:hypercorn,代碼行數:4,代碼來源:context.py

示例15: clear

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Event [as 別名]
def clear(self) -> None:
        self._event = trio.Event() 
開發者ID:pgjones,項目名稱:hypercorn,代碼行數:4,代碼來源:context.py


注:本文中的trio.Event方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。