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


Python typing.Coroutine方法代码示例

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


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

示例1: run_sync

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Coroutine [as 别名]
def run_sync(func: Callable[..., Any]) -> Callable[..., Coroutine[Any, None, None]]:
    """Ensure that the sync function is run within the event loop.

    If the *func* is not a coroutine it will be wrapped such that
    it runs in the default executor (use loop.set_default_executor
    to change). This ensures that synchronous functions do not
    block the event loop.
    """

    @wraps(func)
    async def _wrapper(*args: Any, **kwargs: Any) -> Any:
        loop = asyncio.get_running_loop()
        result = await loop.run_in_executor(
            None, copy_context().run, partial(func, *args, **kwargs)
        )
        if isgenerator(result):
            return run_sync_iterable(result)  # type: ignore
        else:
            return result

    _wrapper._quart_async_wrapper = True  # type: ignore
    return _wrapper 
开发者ID:pgjones,项目名称:quart,代码行数:24,代码来源:utils.py

示例2: sync_arguments_coercer

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Coroutine [as 别名]
def sync_arguments_coercer(
    *coroutines: List[Coroutine],
) -> List[Union[Any, Exception]]:
    """
    Coerce arguments synchronously.

    :param coroutines: list of coroutine to await
    :type coroutines: List[Coroutine]
    :return: the result of coroutines
    :rtype: List[Union[Any, Exception]]
    """
    results = []
    for coroutine in coroutines:
        try:
            result = await coroutine
        except Exception as e:  # pylint: disable=broad-except
            result = e
        results.append(result)
    return results 
开发者ID:tartiflette,项目名称:tartiflette,代码行数:21,代码来源:default.py

示例3: put

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Coroutine [as 别名]
def put(
        self, coro: Coroutine, task_complete: Callable = None, ident: str = None
    ) -> PendingTask:
        """
        Add a new task to the queue, delaying execution if busy.

        Args:
            coro: The coroutine to run
            task_complete: A callback to run on completion
            ident: A string identifier for the task

        Returns: a future resolving to the asyncio task instance once queued

        """
        pending = PendingTask(coro, task_complete, ident)
        if self._cancelled:
            pending.cancel()
        elif self.ready:
            pending.task = self.run(coro, task_complete, pending.ident)
        else:
            self.add_pending(pending)
        return pending 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:24,代码来源:task_queue.py

示例4: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Coroutine [as 别名]
def __init__(
        self,
        context: InjectionContext,
        receive_inbound: Coroutine,
        return_inbound: Callable = None,
    ):
        """Initialize an `InboundTransportManager` instance."""
        self.context = context
        self.max_message_size = 0
        self.receive_inbound = receive_inbound
        self.return_inbound = return_inbound
        self.registered_transports = {}
        self.running_transports = {}
        self.sessions = OrderedDict()
        self.session_limit: asyncio.Semaphore = None
        self.task_queue = TaskQueue()
        self.undelivered_queue: DeliveryQueue = None 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:19,代码来源:manager.py

示例5: queue_message

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Coroutine [as 别名]
def queue_message(
        self,
        inbound_message: InboundMessage,
        send_outbound: Coroutine,
        send_webhook: Coroutine = None,
        complete: Callable = None,
    ) -> PendingTask:
        """
        Add a message to the processing queue for handling.

        Args:
            inbound_message: The inbound message instance
            send_outbound: Async function to send outbound messages
            send_webhook: Async function to dispatch a webhook
            complete: Function to call when the handler has completed

        Returns:
            A pending task instance resolving to the handler task

        """
        return self.put_task(
            self.handle_message(inbound_message, send_outbound, send_webhook), complete
        ) 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:25,代码来源:dispatcher.py

示例6: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Coroutine [as 别名]
def __init__(
        self,
        context: RequestContext,
        inbound_message: InboundMessage,
        send_outbound: Coroutine,
        send_webhook: Coroutine = None,
        **kwargs,
    ):
        """
        Initialize an instance of `DispatcherResponder`.

        Args:
            context: The request context of the incoming message
            inbound_message: The inbound message triggering this handler
            send_outbound: Async function to send outbound message
            send_webhook: Async function to dispatch a webhook

        """
        super().__init__(**kwargs)
        self._context = context
        self._inbound_message = inbound_message
        self._send = send_outbound
        self._webhook = send_webhook 
开发者ID:hyperledger,项目名称:aries-cloudagent-python,代码行数:25,代码来源:dispatcher.py

示例7: __gather_no_exceptions

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Coroutine [as 别名]
def __gather_no_exceptions(tasks: Iterable[Coroutine]):
        """Wrapper around asyncio.gather(*args, return_exception=True)
        Returns list of non-exception items. If every item is exception, raise first of them, else logs them.
        Use case: https://github.com/UncleGoogle/galaxy-integration-humblebundle/issues/59
        """
        items = await asyncio.gather(*tasks, return_exceptions=True)
        if len(items) == 0:
            return []

        err: List[Exception] = []
        ok: List[Any] = []
        for it in items:
            (err if isinstance(it, Exception) else ok).append(it)

        if len(ok) == 0:
            raise err[0]
        if err and len(err) != len(items):
            logger.error(f'Exception(s) occured: [{err}].\nSkipping and going forward')
        return ok 
开发者ID:UncleGoogle,项目名称:galaxy-integration-humblebundle,代码行数:21,代码来源:library.py

示例8: load_account

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Coroutine [as 别名]
def load_account(
        self, account_id: Union[Keypair, str]
    ) -> Union[Account, Coroutine[Any, Any, Account]]:
        """Fetches an account's most current state in the ledger and then creates
        and returns an :class:`stellar_sdk.account.Account` object.

        :param account_id: The account to load.
        :return: an :class:`stellar_sdk.account.Account` object.
        :raises:
            :exc:`ConnectionError <stellar_sdk.exceptions.ConnectionError>`
            :exc:`NotFoundError <stellar_sdk.exceptions.NotFoundError>`
            :exc:`BadRequestError <stellar_sdk.exceptions.BadRequestError>`
            :exc:`BadResponseError <stellar_sdk.exceptions.BadResponseError>`
            :exc:`UnknownRequestError <stellar_sdk.exceptions.UnknownRequestError>`
        """

        if isinstance(account_id, Keypair):
            account = account_id.public_key
        else:
            account = account_id
        if self.__async:
            return self.__load_account_async(account)
        return self.__load_account_sync(account) 
开发者ID:StellarCN,项目名称:py-stellar-base,代码行数:25,代码来源:server.py

示例9: test_coroutine

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Coroutine [as 别名]
def test_coroutine(self):
        ns = {}
        exec(
            "async def foo():\n"
            "    return\n",
            globals(), ns)
        foo = ns['foo']
        g = foo()
        self.assertIsInstance(g, typing.Coroutine)
        with self.assertRaises(TypeError):
            isinstance(g, typing.Coroutine[int])
        self.assertNotIsInstance(foo, typing.Coroutine)
        try:
            g.send(None)
        except StopIteration:
            pass 
开发者ID:ShikyoKira,项目名称:Project-New-Reign---Nemesis-Main,代码行数:18,代码来源:test_typing.py

示例10: cleanup_old_portal_while_bridging

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Coroutine [as 别名]
def cleanup_old_portal_while_bridging(evt: CommandEvent, portal: "po.Portal"
                                            ) -> Tuple[
    bool, Optional[Coroutine[None, None, None]]]:
    if not portal.mxid:
        await evt.reply("The portal seems to have lost its Matrix room between you"
                        "calling `$cmdprefix+sp bridge` and this command.\n\n"
                        "Continuing without touching previous Matrix room...")
        return True, None
    elif evt.args[0] == "delete-and-continue":
        return True, portal.cleanup_portal("Portal deleted (moving to another room)")
    elif evt.args[0] == "unbridge-and-continue":
        return True, portal.cleanup_portal("Room unbridged (portal moving to another room)",
                                           puppets_only=True)
    else:
        await evt.reply(
            "The chat you were trying to bridge already has a Matrix portal room.\n\n"
            "Please use `$cmdprefix+sp delete-and-continue` or `$cmdprefix+sp unbridge-and-"
            "continue` to either delete or unbridge the existing room (respectively) and "
            "continue with the bridging.\n\n"
            "If you changed your mind, use `$cmdprefix+sp cancel` to cancel.")
        return False, None 
开发者ID:tulir,项目名称:mautrix-telegram,代码行数:23,代码来源:bridge.py

示例11: add_background_task

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Coroutine [as 别名]
def add_background_task(self, coroutine: Union[Coroutine, asyncio.Future]):
        """Run a coroutine in the background

        The provided coroutine will be run in the background once
        Lightbus startup is complete.

        The coroutine will be cancelled when the bus client is closed.

        The Lightbus process will exit if the coroutine raises an exception.
        See lightbus.utilities.async_tools.check_for_exception() for details.
        """

        # Store coroutine for starting once the worker starts
        self._background_coroutines.append(coroutine)

    # Utilities 
开发者ID:adamcharnock,项目名称:lightbus,代码行数:18,代码来源:bus_client.py

示例12: block

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Coroutine [as 别名]
def block(coroutine: Coroutine, loop=None, *, timeout=None):
    """Call asynchronous code synchronously

    Note that this cannot be used inside an event loop.
    """
    loop = loop or get_event_loop()
    if loop.is_running():
        if hasattr(coroutine, "close"):
            coroutine.close()
        raise CannotBlockHere(
            "It appears you have tried to use a blocking API method "
            "from within an event loop. Unfortunately this is unsupported. "
            "Instead, use the async version of the method."
        )
    try:
        if timeout is None:
            val = loop.run_until_complete(coroutine)
        else:
            val = loop.run_until_complete(asyncio.wait_for(coroutine, timeout=timeout))
    except Exception as e:
        # The intention here is to get sensible stack traces from exceptions within blocking calls
        raise e
    return val 
开发者ID:adamcharnock,项目名称:lightbus,代码行数:25,代码来源:async_tools.py

示例13: __call__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Coroutine [as 别名]
def __call__(
        self, coro: Optional[Callable[..., Coroutine]] = None, name: str = None
    ) -> Union[Callable[..., Coroutine], "Timeit"]:
        if name:
            child = Timeit(name=name)
            child._transactions = self._transactions
            return child

        if not coro:
            raise ValueError(
                "Invalid method call. " '"coro" or "name" must be provided'
            )

        @wraps(coro)
        async def wrapped(*args, **kwargs):
            async with self:
                return await coro(*args, **kwargs)

        return wrapped 
开发者ID:b2wdigital,项目名称:async-worker,代码行数:21,代码来源:utils.py

示例14: _dispatch_internal

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Coroutine [as 别名]
def _dispatch_internal(
            self, actor_id: ActorId, method_context: ActorMethodContext,
            dispatch_action: Callable[[Actor], Coroutine[Any, Any, Optional[bytes]]]) -> object:
        # Activate actor when actor is invoked.
        if actor_id.id not in self._active_actors:
            await self.activate_actor(actor_id)
        actor = None
        async with self._active_actors_lock:
            actor = self._active_actors.get(actor_id.id, None)
        if not actor:
            raise ValueError(f'{actor_id} is not activated')

        try:
            await actor._on_pre_actor_method_internal(method_context)
            retval = await dispatch_action(actor)
            await actor._on_post_actor_method_internal(method_context)
        except DaprInternalError as ex:
            await actor._on_invoke_failed_internal(ex)
            raise ex

        return retval 
开发者ID:dapr,项目名称:python-sdk,代码行数:23,代码来源:manager.py

示例15: exec_async_tasks

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Coroutine [as 别名]
def exec_async_tasks(tasks: List[Coroutine]) -> List[Union[None, str]]:
    """
    Execute tasks asynchronously
    """
    # TODO: asyncio API is nicer in python 3.7
    if platform.system() == 'Windows':
        loop = asyncio.ProactorEventLoop()
        asyncio.set_event_loop(loop)
    else:
        loop = asyncio.get_event_loop()

    try:
        errors = loop.run_until_complete(asyncio.gather(*tasks))
    finally:
        loop.close()
    return errors 
开发者ID:nosarthur,项目名称:gita,代码行数:18,代码来源:utils.py


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