当前位置: 首页>>代码示例>>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;未经允许,请勿转载。