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


Python typing.Awaitable方法代码示例

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


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

示例1: execute

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Awaitable [as 别名]
def execute(
        self, document: DocumentNode, *args, **kwargs,
    ) -> ExecutionResult:
        """Execute the provided document AST for on a local GraphQL Schema.
        """

        result_or_awaitable = execute(self.schema, document, *args, **kwargs)

        execution_result: ExecutionResult

        if isawaitable(result_or_awaitable):
            result_or_awaitable = cast(Awaitable[ExecutionResult], result_or_awaitable)
            execution_result = await result_or_awaitable
        else:
            result_or_awaitable = cast(ExecutionResult, result_or_awaitable)
            execution_result = result_or_awaitable

        return execution_result 
开发者ID:graphql-python,项目名称:gql,代码行数:20,代码来源:local_schema.py

示例2: sync_with_context

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Awaitable [as 别名]
def sync_with_context(future: Awaitable) -> Any:
    context = None
    if _request_ctx_stack.top is not None:
        context = _request_ctx_stack.top.copy()
    elif _websocket_ctx_stack.top is not None:
        context = _websocket_ctx_stack.top.copy()
    elif _app_ctx_stack.top is not None:
        context = _app_ctx_stack.top.copy()

    async def context_wrapper() -> Any:
        if context is not None:
            async with context:
                return await future
        else:
            return await future

    return asyncio.get_event_loop().sync_wait(context_wrapper())  # type: ignore 
开发者ID:pgjones,项目名称:quart,代码行数:19,代码来源:_synchronise.py

示例3: receive_activity_internal

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Awaitable [as 别名]
def receive_activity_internal(
        self,
        context: TurnContext,
        callback: Callable[[TurnContext], Awaitable],
        next_middleware_index: int = 0,
    ):
        if next_middleware_index == len(self._middleware):
            if callback is not None:
                return await callback(context)
            return None
        next_middleware = self._middleware[next_middleware_index]

        async def call_next_middleware():
            return await self.receive_activity_internal(
                context, callback, next_middleware_index + 1
            )

        try:
            return await next_middleware.on_turn(context, call_next_middleware)
        except Exception as error:
            raise error 
开发者ID:microsoft,项目名称:botbuilder-python,代码行数:23,代码来源:middleware_set.py

示例4: test_middleware_set_receive_activity_internal

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Awaitable [as 别名]
def test_middleware_set_receive_activity_internal(self):
        class PrintMiddleware:
            async def on_turn(self, context_or_string, next_middleware):
                print("PrintMiddleware says: %s." % context_or_string)
                return next_middleware

        class ModifyInputMiddleware(Middleware):
            async def on_turn(
                self, context: TurnContext, logic: Callable[[TurnContext], Awaitable]
            ):
                context = "Hello"
                print(context)
                print("Here is the current context_or_string: %s" % context)
                return logic

        async def request_handler(context_or_string):
            assert context_or_string == "Hello"

        middleware_set = MiddlewareSet().use(PrintMiddleware())
        middleware_set.use(ModifyInputMiddleware())

        await middleware_set.receive_activity_internal("Bye", request_handler) 
开发者ID:microsoft,项目名称:botbuilder-python,代码行数:24,代码来源:test_middleware_set.py

示例5: respond

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Awaitable [as 别名]
def respond(self, content: Union[str, MessageEventContent],
                event_type: EventType = EventType.ROOM_MESSAGE, markdown: bool = True,
                allow_html: bool = False, reply: Union[bool, str] = False,
                edits: Optional[Union[EventID, MessageEvent]] = None) -> Awaitable[EventID]:
        if isinstance(content, str):
            content = TextMessageEventContent(msgtype=MessageType.NOTICE, body=content)
            if allow_html or markdown:
                content.format = Format.HTML
                content.body, content.formatted_body = parse_formatted(content.body,
                                                                       render_markdown=markdown,
                                                                       allow_html=allow_html)
        if edits:
            content.set_edit(edits)
        elif reply:
            if reply != "force" and self.disable_reply:
                content.body = f"{self.sender}: {content.body}"
                fmt_body = content.formatted_body or escape(content.body).replace("\n", "<br>")
                content.formatted_body = (f'<a href="https://matrix.to/#/{self.sender}">'
                                          f'{self.sender}'
                                          f'</a>: {fmt_body}')
            else:
                content.set_reply(self)
        return self.client.send_message_event(self.room_id, event_type, content) 
开发者ID:maubot,项目名称:maubot,代码行数:25,代码来源:matrix.py

示例6: wait_first

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Awaitable [as 别名]
def wait_first(
        self,
        *awaitables: Awaitable[_TReturn],
        token: CancelToken = None,
        timeout: float = None
    ) -> _TReturn:
        """
        Wait for the first awaitable to complete, unless we timeout or the token chain is triggered.

        The given token is chained with this service's token, so triggering either will cancel
        this.

        Returns the result of the first one to complete.

        Raises TimeoutError if we timeout or OperationCancelled if the token chain is triggered.

        All pending futures are cancelled before returning.
        """
        if token is None:
            token_chain = self.cancel_token
        else:
            token_chain = token.chain(self.cancel_token)
        return await token_chain.cancellable_wait(*awaitables, timeout=timeout) 
开发者ID:QuarkChain,项目名称:pyquarkchain,代码行数:25,代码来源:cancellable.py

示例7: run_daemon_task

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Awaitable [as 别名]
def run_daemon_task(self, awaitable: Awaitable[Any]) -> None:
        """Run the given awaitable in the background.

        Like :meth:`run_task` but if the task ends without cancelling, then this
        this service will terminate as well.
        """

        @functools.wraps(awaitable)  # type: ignore
        async def _run_daemon_task_wrapper() -> None:
            try:
                await awaitable
            finally:
                if not self.is_cancelled:
                    # self.logger.debug(
                    #     "%s finished while %s is still running, terminating as well"
                    #     % (awaitable, self)
                    # )
                    self.cancel_token.trigger()

        self.run_task(_run_daemon_task_wrapper()) 
开发者ID:QuarkChain,项目名称:pyquarkchain,代码行数:22,代码来源:service.py

示例8: resolve

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Awaitable [as 别名]
def resolve(
        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
    ) -> Awaitable[List[Tuple[int, Any]]]:
        """Resolves an address.

        The ``host`` argument is a string which may be a hostname or a
        literal IP address.

        Returns a `.Future` whose result is a list of (family,
        address) pairs, where address is a tuple suitable to pass to
        `socket.connect <socket.socket.connect>` (i.e. a ``(host,
        port)`` pair for IPv4; additional fields may be present for
        IPv6). If a ``callback`` is passed, it will be run with the
        result as an argument when it is complete.

        :raises IOError: if the address cannot be resolved.

        .. versionchanged:: 4.4
           Standardized all implementations to raise `IOError`.

        .. versionchanged:: 6.0 The ``callback`` argument was removed.
           Use the returned awaitable object instead.

        """
        raise NotImplementedError() 
开发者ID:opendevops-cn,项目名称:opendevops,代码行数:27,代码来源:netutil.py

示例9: wait

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Awaitable [as 别名]
def wait(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[bool]:
        """Wait for `.notify`.

        Returns a `.Future` that resolves ``True`` if the condition is notified,
        or ``False`` after a timeout.
        """
        waiter = Future()  # type: Future[bool]
        self._waiters.append(waiter)
        if timeout:

            def on_timeout() -> None:
                if not waiter.done():
                    future_set_result_unless_cancelled(waiter, False)
                self._garbage_collect()

            io_loop = ioloop.IOLoop.current()
            timeout_handle = io_loop.add_timeout(timeout, on_timeout)
            waiter.add_done_callback(lambda _: io_loop.remove_timeout(timeout_handle))
        return waiter 
开发者ID:opendevops-cn,项目名称:opendevops,代码行数:21,代码来源:locks.py

示例10: headers_received

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Awaitable [as 别名]
def headers_received(
        self,
        start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine],
        headers: httputil.HTTPHeaders,
    ) -> Optional[Awaitable[None]]:
        assert isinstance(start_line, httputil.RequestStartLine)
        request = httputil.HTTPServerRequest(
            connection=self.request_conn,
            server_connection=self.server_conn,
            start_line=start_line,
            headers=headers,
        )

        self.delegate = self.router.find_handler(request)
        if self.delegate is None:
            app_log.debug(
                "Delegate for %s %s request not found",
                start_line.method,
                start_line.path,
            )
            self.delegate = _DefaultMessageDelegate(self.request_conn)

        return self.delegate.headers_received(start_line, headers) 
开发者ID:opendevops-cn,项目名称:opendevops,代码行数:25,代码来源:routing.py

示例11: handle_stream

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Awaitable [as 别名]
def handle_stream(
        self, stream: IOStream, address: tuple
    ) -> Optional[Awaitable[None]]:
        """Override to handle a new `.IOStream` from an incoming connection.

        This method may be a coroutine; if so any exceptions it raises
        asynchronously will be logged. Accepting of incoming connections
        will not be blocked by this coroutine.

        If this `TCPServer` is configured for SSL, ``handle_stream``
        may be called before the SSL handshake has completed. Use
        `.SSLIOStream.wait_for_handshake` if you need to verify the client's
        certificate or use NPN/ALPN.

        .. versionchanged:: 4.2
           Added the option for this method to be a coroutine.
        """
        raise NotImplementedError() 
开发者ID:opendevops-cn,项目名称:opendevops,代码行数:20,代码来源:tcpserver.py

示例12: create_session

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Awaitable [as 别名]
def create_session(
        self,
        *,
        accept_undelivered: bool = False,
        can_respond: bool = False,
        client_info: dict = None,
        wire_format: BaseWireFormat = None,
    ) -> Awaitable[InboundSession]:
        """
        Create a new inbound session.

        Args:
            accept_undelivered: Flag for accepting undelivered messages
            can_respond: Flag indicating that the transport can send responses
            client_info: Request-specific client information
            wire_format: Optionally override the session wire format
        """
        return self._create_session(
            accept_undelivered=accept_undelivered,
            can_respond=can_respond,
            client_info=client_info,
            wire_format=wire_format or self.wire_format,
            transport_type=self.scheme,
        ) 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:26,代码来源:base.py

示例13: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Awaitable [as 别名]
def __init__(self, **kwargs):
        """initial function

        :param target:      target of timer
        :param duration:    duration for checking timeout
        :param start_time:  start time of timer
        :param is_repeat:   if true, the timer runs repeatedly
        :param callback:    callback function after timeout or normal case
        :param kwargs:      parameters for callback function
        """
        self.target = kwargs.get("target")
        self.duration = kwargs.get("duration")
        self.is_run_at_start: bool = kwargs.get("is_run_at_start", False)
        self._is_repeat: bool = kwargs.get("is_repeat", False)

        # only works If is_repeat=True. 0 means no timeout.
        self._repeat_timeout: int = kwargs.get("repeat_timeout", 0)

        self.__start_time = time.time()
        self.__repeat_start_time = self.__start_time
        self.__callback: Union[Callable, Awaitable] = kwargs.get("callback", None)
        self.__kwargs = kwargs.get("callback_kwargs") or {} 
开发者ID:icon-project,项目名称:loopchain,代码行数:24,代码来源:timer_service.py

示例14: new_ensure_async

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Awaitable [as 别名]
def new_ensure_async(  # type: ignore
    self, func: Callable[..., Any]
) -> Callable[..., Awaitable[Any]]:
    if is_coroutine_function(func):
        return func
    else:
        return asyncio.coroutine(func) 
开发者ID:pgjones,项目名称:quart,代码行数:9,代码来源:app.py

示例15: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Awaitable [as 别名]
def __init__(
        self,
        required_endorsements: List[str] = None,
        claims_validator: Callable[[List[Dict]], Awaitable] = None,
    ):
        self.required_endorsements = required_endorsements or []
        self.claims_validator = claims_validator 
开发者ID:microsoft,项目名称:botbuilder-python,代码行数:9,代码来源:authentication_configuration.py


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