當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。