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


Python inspect.isawaitable方法代碼示例

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


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

示例1: execute

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isawaitable [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: _run_response_middleware

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isawaitable [as 別名]
def _run_response_middleware(
        self, request, response, request_name=None
    ):
        named_middleware = self.named_response_middleware.get(
            request_name, deque()
        )
        applicable_middleware = self.response_middleware + named_middleware
        if applicable_middleware:
            for middleware in applicable_middleware:
                _response = middleware(request, response)
                if isawaitable(_response):
                    _response = await _response
                if _response:
                    response = _response
                    break
        return response 
開發者ID:huge-success,項目名稱:sanic,代碼行數:18,代碼來源:app.py

示例3: shutdown

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isawaitable [as 別名]
def shutdown(self) -> None:
        """
        Gather the listeners to fire on server stop.
        Because we are using a third-party server and not Sanic server, we do
        not have access to fire anything AFTER the server stops.
        Therefore, we fire before_server_stop and after_server_stop
        in sequence since the ASGI lifespan protocol only supports a single
        shutdown event.
        """
        listeners = self.asgi_app.sanic_app.listeners.get(
            "before_server_stop", []
        ) + self.asgi_app.sanic_app.listeners.get("after_server_stop", [])

        for handler in listeners:
            response = handler(
                self.asgi_app.sanic_app, self.asgi_app.sanic_app.loop
            )
            if isawaitable(response):
                await response 
開發者ID:huge-success,項目名稱:sanic,代碼行數:21,代碼來源:asgi.py

示例4: _bake_module

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isawaitable [as 別名]
def _bake_module(
    module: object, schema_name: str, config: Optional[Dict[str, Any]] = None
) -> str:
    """
    Bakes a module and retrieves its extra SDL content.
    :param module: module instance to bake
    :param schema_name: schema name to link with
    :param config: configuration of the module
    :type module: object
    :type schema_name: str
    :type config: Optional[Dict[str, Any]]
    :return: the extra SDL provided by the module
    :rtype: str
    """
    msdl = module.bake(schema_name, config)
    if isawaitable(msdl):
        msdl = await msdl
    return msdl or "" 
開發者ID:tartiflette,項目名稱:tartiflette,代碼行數:20,代碼來源:engine.py

示例5: check_filter

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isawaitable [as 別名]
def check_filter(filter_, args):
    """
    Helper for executing filter

    :param filter_:
    :param args:
    :param kwargs:
    :return:
    """
    if not callable(filter_):
        raise TypeError(f'Filter must be callable and/or awaitable! Error with {filter_}')

    if inspect.isawaitable(filter_) or inspect.iscoroutinefunction(filter_):
        return await filter_(*args)
    else:
        return filter_(*args) 
開發者ID:mahenzon,項目名稱:aioalice,代碼行數:18,代碼來源:filters.py

示例6: _parse_html

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isawaitable [as 別名]
def _parse_html(cls, *, html_etree: etree._Element):
        if html_etree is None:
            raise ValueError("<Item: html_etree is expected>")
        item_ins = cls()
        fields_dict = getattr(item_ins, "__fields", {})
        for field_name, field_value in fields_dict.items():
            if not field_name.startswith("target_"):
                clean_method = getattr(item_ins, f"clean_{field_name}", None)
                value = field_value.extract(html_etree)
                if clean_method is not None and callable(clean_method):
                    try:
                        aws_clean_func = clean_method(value)
                        if isawaitable(aws_clean_func):
                            value = await aws_clean_func
                        else:
                            raise InvalidFuncType(
                                f"<Item: clean_method must be a coroutine function>"
                            )
                    except IgnoreThisItem:
                        item_ins.ignore_item = True

                setattr(item_ins, field_name, value)
                item_ins.results[field_name] = value
        return item_ins 
開發者ID:howie6879,項目名稱:ruia,代碼行數:26,代碼來源:item.py

示例7: ensure_future

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isawaitable [as 別名]
def ensure_future(coro_or_future, *, loop=None):
    """Wrap a coroutine or an awaitable in a future.

    If the argument is a Future, it is returned directly.
    """
    if isinstance(coro_or_future, futures.Future):
        if loop is not None and loop is not coro_or_future._loop:
            raise ValueError('loop argument must agree with Future')
        return coro_or_future
    elif coroutines.iscoroutine(coro_or_future):
        if loop is None:
            loop = events.get_event_loop()
        task = loop.create_task(coro_or_future)
        if task._source_traceback:
            del task._source_traceback[-1]
        return task
    elif compat.PY35 and inspect.isawaitable(coro_or_future):
        return ensure_future(_wrap_awaitable(coro_or_future), loop=loop)
    else:
        raise TypeError('A Future, a coroutine or an awaitable is required') 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:22,代碼來源:tasks.py

示例8: test_isawaitable

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isawaitable [as 別名]
def test_isawaitable(self):
        def gen(): yield
        self.assertFalse(inspect.isawaitable(gen()))

        coro = coroutine_function_example(1)
        gen_coro = gen_coroutine_function_example(1)

        self.assertTrue(inspect.isawaitable(coro))
        self.assertTrue(inspect.isawaitable(gen_coro))

        class Future:
            def __await__():
                pass
        self.assertTrue(inspect.isawaitable(Future()))
        self.assertFalse(inspect.isawaitable(Future))

        class NotFuture: pass
        not_fut = NotFuture()
        not_fut.__await__ = lambda: None
        self.assertFalse(inspect.isawaitable(not_fut))

        coro.close(); gen_coro.close() # silence warnings 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:24,代碼來源:test_inspect.py

示例9: ensure_future

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isawaitable [as 別名]
def ensure_future(coro_or_future, *, loop=None):
    """Wrap a coroutine or an awaitable in a future.

    If the argument is a Future, it is returned directly.
    """
    if coroutines.iscoroutine(coro_or_future):
        if loop is None:
            loop = events.get_event_loop()
        task = loop.create_task(coro_or_future)
        if task._source_traceback:
            del task._source_traceback[-1]
        return task
    elif futures.isfuture(coro_or_future):
        if loop is not None and loop is not futures._get_loop(coro_or_future):
            raise ValueError('loop argument must agree with Future')
        return coro_or_future
    elif inspect.isawaitable(coro_or_future):
        return ensure_future(_wrap_awaitable(coro_or_future), loop=loop)
    else:
        raise TypeError('An asyncio.Future, a coroutine or an awaitable is '
                        'required') 
開發者ID:CedricGuillemet,項目名稱:Imogen,代碼行數:23,代碼來源:tasks.py

示例10: download_file

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isawaitable [as 別名]
def download_file(
    self: TelegramClient, location: TypeLocation,
    out: BinaryIO, progress_callback: callable = None
) -> BinaryIO:
    size = location.size
    dc_id, location = utils.get_input_location(location)
    # We lock the transfers because telegram has connection count limits
    downloader = ParallelTransferrer(self, dc_id)
    downloaded = downloader.download(location, size)
    async for x in downloaded:
        out.write(x)
        if progress_callback:
            r = progress_callback(out.tell(), size)
            if inspect.isawaitable(r):
                await r

    return out 
開發者ID:TG-UserBot,項目名稱:TG-UserBot,代碼行數:19,代碼來源:FastTelethon.py

示例11: wrap_generator

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isawaitable [as 別名]
def wrap_generator(func):
    """
    Decorator to convert a generator function to an async function which collects
    and returns generator results, returning a list if there are multiple results
    """

    async def _wrapped(*a, **k):
        r, ret = None, []
        gen = func(*a, **k)
        while True:
            try:
                item = gen.send(r)
            except StopIteration:
                break
            if inspect.isawaitable(item):
                r = await item
            else:
                r = item
            ret.append(r)

        if len(ret) == 1:
            return ret.pop()
        return ret

    return _wrapped 
開發者ID:peeringdb,項目名稱:peeringdb-py,代碼行數:27,代碼來源:_tasks_async.py

示例12: evaluate

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isawaitable [as 別名]
def evaluate(_cmd, pld):
    """
    :param _cmd: The command object referenced in the command.
    :type _cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if pld.args:
        try:
            execution = " ".join(pld.args)
            output = eval(execution)
            if inspect.isawaitable(output):
                output = await output
            response = ok('Executed')
            response.description = f'```py\n{output}\n```'
        except Exception as e:
            response = error('Error')
            response.description = f'```py\n{e}\n```'
    else:
        response = error('Nothing inputted.')
    await pld.msg.channel.send(embed=response) 
開發者ID:lu-ci,項目名稱:apex-sigma-core,代碼行數:23,代碼來源:evaluate.py

示例13: describe_transfers

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isawaitable [as 別名]
def describe_transfers(translist: list, getter):
    """

    :param translist:
    :type translist:
    :param getter:
    :type getter:
    :return:
    :rtype:
    """
    described = []
    for transitem in translist:
        transobject = await getter(int(transitem[0])) if inspect.isawaitable(getter) else getter(int(transitem[0]))
        transobject = await transobject if inspect.isawaitable(transobject) else transobject
        if transobject:
            addition = [transobject.name, transitem[1]]
        else:
            addition = transitem
        described.append(addition)
    return described 
開發者ID:lu-ci,項目名稱:apex-sigma-core,代碼行數:22,代碼來源:resourcestatistics.py

示例14: gather

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isawaitable [as 別名]
def gather(
    *aws: Sequence[Awaitable],
    loop: Optional[asyncio.AbstractEventLoop] = None,
    return_exceptions: bool = False,
) -> List[Any]:
    """A function that is calling :func:`asyncio.gather`.

    Used for less imports inside and outside gd.py.

    One small addition is that a sequence of awaitables can be given
    as the only positional argument.

    This way, :func:`asyncio.gather` will be run on that sequence.
    """
    if len(aws) == 1:
        maybe_aw = aws[0]
        if not inspect.isawaitable(maybe_aw):
            aws = maybe_aw

    return await asyncio.gather(*aws, loop=loop, return_exceptions=return_exceptions) 
開發者ID:NeKitDS,項目名稱:gd.py,代碼行數:22,代碼來源:async_utils.py

示例15: test_create_asyncio_server

# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import isawaitable [as 別名]
def test_create_asyncio_server(app):
    if not uvloop_installed():
        loop = asyncio.get_event_loop()
        asyncio_srv_coro = app.create_server(return_asyncio_server=True)
        assert isawaitable(asyncio_srv_coro)
        srv = loop.run_until_complete(asyncio_srv_coro)
        assert srv.is_serving() is True 
開發者ID:huge-success,項目名稱:sanic,代碼行數:9,代碼來源:test_app.py


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