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


Python asyncio.TimeoutError方法代码示例

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


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

示例1: _send_init_message_and_wait_ack

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import TimeoutError [as 别名]
def _send_init_message_and_wait_ack(self) -> None:
        """Send init message to the provided websocket and wait for the connection ACK.

        If the answer is not a connection_ack message, we will return an Exception.
        """

        init_message = json.dumps(
            {"type": "connection_init", "payload": self.init_payload}
        )

        await self._send(init_message)

        # Wait for the connection_ack message or raise a TimeoutError
        init_answer = await asyncio.wait_for(self._receive(), self.ack_timeout)

        answer_type, answer_id, execution_result = self._parse_answer(init_answer)

        if answer_type != "connection_ack":
            raise TransportProtocolError(
                "Websocket server did not return a connection ack"
            ) 
开发者ID:graphql-python,项目名称:gql,代码行数:23,代码来源:websockets.py

示例2: fetch

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import TimeoutError [as 别名]
def fetch(self, session, room, id_blacklist):
        url = self._stream_api.format(room=room)
        while True:
            # print("polling on url %s" % url)
            try:
                with aiohttp.Timeout(300):
                    async with session.get(url, headers=self.headers) as resp:
                        while True:
                            line = await resp.content.readline()
                            line = bytes.decode(line, 'utf-8').strip()
                            if not line:
                                continue
                            msg = self.parse_jmsg(room, json.loads(line))
                            if msg.sender in id_blacklist:
                                continue
                            self.send_to_bus(msg)
            except asyncio.TimeoutError:
                pass
            except:
                raise 
开发者ID:tuna,项目名称:fishroom,代码行数:22,代码来源:gitter.py

示例3: _clean_close

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import TimeoutError [as 别名]
def _clean_close(self, e: Exception) -> None:
        """Coroutine which will:

        - send stop messages for each active subscription to the server
        - send the connection terminate message
        """

        # Send 'stop' message for all current queries
        for query_id, listener in self.listeners.items():

            if listener.send_stop:
                await self._send_stop_message(query_id)
                listener.send_stop = False

        # Wait that there is no more listeners (we received 'complete' for all queries)
        try:
            await asyncio.wait_for(self._no_more_listeners.wait(), self.close_timeout)
        except asyncio.TimeoutError:  # pragma: no cover
            pass

        # Finally send the 'connection_terminate' message
        await self._send_connection_terminate_message() 
开发者ID:graphql-python,项目名称:gql,代码行数:24,代码来源:websockets.py

示例4: _parse_sdcard_list

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import TimeoutError [as 别名]
def _parse_sdcard_list(self, done_cb):
        self.log.debug('Comms: _parse_sdcard_list')

        # setup callback to receive and parse listing data
        files = []
        f = asyncio.Future()
        self.redirect_incoming(lambda x: self._rcv_sdcard_line(x, files, f))

        # issue command
        self._write('M20\n')

        # wait for it to complete and get all the lines
        # add a long timeout in case it fails and we don't want to wait for ever
        try:
            await asyncio.wait_for(f, 10)

        except asyncio.TimeoutError:
            self.log.warning("Comms: Timeout waiting for sd card list")
            files = []

        self.redirect_incoming(None)

        # call upstream callback with results
        done_cb(files) 
开发者ID:wolfmanjm,项目名称:kivy-smoothie-host,代码行数:26,代码来源:comms.py

示例5: _connect

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import TimeoutError [as 别名]
def _connect(self, timeout=None, ssl=None):
        await super()._connect(timeout=timeout, ssl=ssl)

        # Wait for EOF for 2 seconds (or if _wait_for_data's definition
        # is missing or different, just sleep for 2 seconds). This way
        # we give the proxy a chance to close the connection if the current
        # codec (which the proxy detects with the data we sent) cannot
        # be used for this proxy. This is a work around for #1134.
        # TODO Sleeping for N seconds may not be the best solution
        # TODO This fix could be welcome for HTTP proxies as well
        try:
            await asyncio.wait_for(self._reader._wait_for_data('proxy'), 2)
        except asyncio.TimeoutError:
            pass
        except Exception:
            await asyncio.sleep(2)

        if self._reader.at_eof():
            await self.disconnect()
            raise ConnectionError(
                'Proxy closed the connection after sending initial payload') 
开发者ID:LonamiWebs,项目名称:Telethon,代码行数:23,代码来源:tcpmtproxy.py

示例6: help_cleanup

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import TimeoutError [as 别名]
def help_cleanup(bot: Bot, author: Member, message: Message) -> None:
    """
    Runs the cleanup for the help command.

    Adds the :trashcan: reaction that, when clicked, will delete the help message.
    After a 300 second timeout, the reaction will be removed.
    """
    def check(reaction: Reaction, user: User) -> bool:
        """Checks the reaction is :trashcan:, the author is original author and messages are the same."""
        return str(reaction) == DELETE_EMOJI and user.id == author.id and reaction.message.id == message.id

    await message.add_reaction(DELETE_EMOJI)

    try:
        await bot.wait_for("reaction_add", check=check, timeout=300)
        await message.delete()
    except TimeoutError:
        await message.remove_reaction(DELETE_EMOJI, bot.user)
    except NotFound:
        pass 
开发者ID:python-discord,项目名称:bot,代码行数:22,代码来源:help.py

示例7: _connect_sentinel

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import TimeoutError [as 别名]
def _connect_sentinel(self, address, timeout, pools):
        """Try to connect to specified Sentinel returning either
        connections pool or exception.
        """
        try:
            with async_timeout(timeout):
                pool = await create_pool(
                    address, minsize=1, maxsize=2,
                    parser=self._parser_class,
                    )
            pools.append(pool)
            return pool
        except asyncio.TimeoutError as err:
            sentinel_logger.debug(
                "Failed to connect to Sentinel(%r) within %ss timeout",
                address, timeout)
            return err
        except Exception as err:
            sentinel_logger.debug(
                "Error connecting to Sentinel(%r): %r", address, err)
            return err 
开发者ID:aio-libs,项目名称:aioredis,代码行数:23,代码来源:pool.py

示例8: test_create_no_minsize

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import TimeoutError [as 别名]
def test_create_no_minsize(create_pool, server):
    pool = await create_pool(
        server.tcp_address,
        minsize=0, maxsize=1)
    assert pool.size == 0
    assert pool.freesize == 0

    with (await pool):
        assert pool.size == 1
        assert pool.freesize == 0

        with pytest.raises(asyncio.TimeoutError):
            await asyncio.wait_for(pool.acquire(),
                                   timeout=0.2)
    assert pool.size == 1
    assert pool.freesize == 1 
开发者ID:aio-libs,项目名称:aioredis,代码行数:18,代码来源:pool_test.py

示例9: simple_db_mutate_returning_item

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import TimeoutError [as 别名]
def simple_db_mutate_returning_item(result_cls, context, mutation_query, *,
                                          item_query, item_cls):
    async with context['dbpool'].acquire() as conn, conn.begin():
        try:
            result = await conn.execute(mutation_query)
            if result.rowcount > 0:
                result = await conn.execute(item_query)
                item = await result.first()
                return result_cls(True, 'success', item_cls.from_row(item))
            else:
                return result_cls(False, 'no matching record', None)
        except (pg.IntegrityError, sa.exc.IntegrityError) as e:
            return result_cls(False, f'integrity error: {e}', None)
        except (asyncio.CancelledError, asyncio.TimeoutError):
            raise
        except Exception as e:
            return result_cls(False, f'unexpected error: {e}', None) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:19,代码来源:base.py

示例10: on_message

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import TimeoutError [as 别名]
def on_message(self, message):
        # we do not want the bot to reply to itself
        if message.author.id == self.user.id:
            return

        if message.content.startswith('$guess'):
            await message.channel.send('Guess a number between 1 and 10.')

            def is_correct(m):
                return m.author == message.author and m.content.isdigit()

            answer = random.randint(1, 10)

            try:
                guess = await self.wait_for('message', check=is_correct, timeout=5.0)
            except asyncio.TimeoutError:
                return await message.channel.send('Sorry, you took too long it was {}.'.format(answer))

            if int(guess.content) == answer:
                await message.channel.send('You are right!')
            else:
                await message.channel.send('Oops. It is actually {}.'.format(answer)) 
开发者ID:Rapptz,项目名称:discord.py,代码行数:24,代码来源:guessing_game.py

示例11: request_offline_members

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import TimeoutError [as 别名]
def request_offline_members(self, guilds):
        # get all the chunks
        chunks = []
        for guild in guilds:
            chunks.extend(self.chunks_needed(guild))

        # we only want to request ~75 guilds per chunk request.
        splits = [guilds[i:i + 75] for i in range(0, len(guilds), 75)]
        for split in splits:
            await self.chunker([g.id for g in split])

        # wait for the chunks
        if chunks:
            try:
                await utils.sane_wait_for(chunks, timeout=len(chunks) * 30.0)
            except asyncio.TimeoutError:
                log.warning('Somehow timed out waiting for chunks.')
            else:
                log.info('Finished requesting guild member chunks for %d guilds.', len(guilds)) 
开发者ID:Rapptz,项目名称:discord.py,代码行数:21,代码来源:state.py

示例12: character_delete

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import TimeoutError [as 别名]
def character_delete(self, ctx, *, name):
        """Deletes a character."""
        user_characters = await self.bot.mdb.characters.find(
            {"owner": str(ctx.author.id)}, ['name', 'upstream']
        ).to_list(None)
        if not user_characters:
            return await ctx.send('You have no characters.')

        selected_char = await search_and_select(ctx, user_characters, name, lambda e: e['name'],
                                                selectkey=lambda e: f"{e['name']} (`{e['upstream']}`)")

        await ctx.send(f"Are you sure you want to delete {selected_char['name']}? (Reply with yes/no)")
        try:
            reply = await self.bot.wait_for('message', timeout=30, check=auth_and_chan(ctx))
        except asyncio.TimeoutError:
            reply = None
        reply = get_positivity(reply.content) if reply is not None else None
        if reply is None:
            return await ctx.send('Timed out waiting for a response or invalid response.')
        elif reply:
            await Character.delete(ctx, str(ctx.author.id), selected_char['upstream'])
            return await ctx.send(f"{selected_char['name']} has been deleted.")
        else:
            return await ctx.send("OK, cancelling.") 
开发者ID:avrae,项目名称:avrae,代码行数:26,代码来源:sheetManager.py

示例13: transferchar

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import TimeoutError [as 别名]
def transferchar(self, ctx, user: discord.Member):
        """Gives a copy of the active character to another user."""
        character: Character = await Character.from_ctx(ctx)
        overwrite = ''

        conflict = await self.bot.mdb.characters.find_one({"owner": str(user.id), "upstream": character.upstream})
        if conflict:
            overwrite = "**WARNING**: This will overwrite an existing character."

        await ctx.send(f"{user.mention}, accept a copy of {character.name}? (Type yes/no)\n{overwrite}")
        try:
            m = await self.bot.wait_for('message', timeout=300,
                                        check=lambda msg: msg.author == user
                                                          and msg.channel == ctx.channel
                                                          and get_positivity(msg.content) is not None)
        except asyncio.TimeoutError:
            m = None

        if m is None or not get_positivity(m.content): return await ctx.send("Transfer not confirmed, aborting.")

        character.owner = str(user.id)
        await character.commit(ctx)
        await ctx.send(f"Copied {character.name} to {user.display_name}'s storage.") 
开发者ID:avrae,项目名称:avrae,代码行数:25,代码来源:sheetManager.py

示例14: confirm

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import TimeoutError [as 别名]
def confirm(ctx, message, delete_msgs=False):
    """
    Confirms whether a user wants to take an action.
    :rtype: bool|None
    :param ctx: The current Context.
    :param message: The message for the user to confirm.
    :param delete_msgs: Whether to delete the messages.
    :return: Whether the user confirmed or not. None if no reply was recieved
    """
    msg = await ctx.channel.send(message)
    try:
        reply = await ctx.bot.wait_for('message', timeout=30, check=auth_and_chan(ctx))
    except asyncio.TimeoutError:
        return None
    replyBool = get_positivity(reply.content) if reply is not None else None
    if delete_msgs:
        try:
            await msg.delete()
            await reply.delete()
        except:
            pass
    return replyBool 
开发者ID:avrae,项目名称:avrae,代码行数:24,代码来源:functions.py

示例15: read_messages

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import TimeoutError [as 别名]
def read_messages(self, stream_name: str, options: Optional[ReadMessagesOptions] = None) -> List[Message]:
        """
        Read message(s) from a chosen stream with options. If no options are specified it will try to read
        1 message from the stream.

        :param stream_name: The name of the stream to read from.
        :param options: (Optional) Options used when reading from the stream of type :class:`.data.ReadMessagesOptions`.
            Defaults are:

            * desired_start_sequence_number: 0,
            * min_message_count: 1,
            * max_message_count: 1,
            * read_timeout_millis: 0 ``# Where 0 here represents that the server will immediately return the messages``
                                     ``# or an exception if there were not enough messages available.``
            If desired_start_sequence_number is specified in the options and is less
            than the current beginning of the stream, returned messages will start
            at the beginning of the stream and not necessarily the desired_start_sequence_number.
        :return: List of at least 1 message.
        :raises: :exc:`~.exceptions.StreamManagerException` and subtypes based on the precise error.
        :raises: :exc:`asyncio.TimeoutError` if the request times out.
        :raises: :exc:`ConnectionError` if the client is unable to reconnect to the server.
        """
        self.__check_closed()
        return Util.sync(self._read_messages(stream_name, options), loop=self.__loop) 
开发者ID:aws,项目名称:aws-greengrass-core-sdk-python,代码行数:26,代码来源:streammanagerclient.py


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