本文整理汇总了Python中asyncio.wait_for方法的典型用法代码示例。如果您正苦于以下问题:Python asyncio.wait_for方法的具体用法?Python asyncio.wait_for怎么用?Python asyncio.wait_for使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类asyncio
的用法示例。
在下文中一共展示了asyncio.wait_for方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wait_for
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import wait_for [as 别名]
def wait_for(self, event, predicate, result=None):
"""Waits for a DISPATCH'd event that meets the predicate.
Parameters
-----------
event: :class:`str`
The event name in all upper case to wait for.
predicate
A function that takes a data parameter to check for event
properties. The data parameter is the 'd' key in the JSON message.
result
A function that takes the same data parameter and executes to send
the result to the future. If ``None``, returns the data.
Returns
--------
asyncio.Future
A future to wait for.
"""
future = self.loop.create_future()
entry = EventListener(event=event, predicate=predicate, result=result, future=future)
self._dispatch_listeners.append(entry)
return future
示例2: _send_init_message_and_wait_ack
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import wait_for [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"
)
示例3: _clean_close
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import wait_for [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()
示例4: test_http_completion
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import wait_for [as 别名]
def test_http_completion() -> None:
# Ensure that the connecion callable returns on completion
app = Quart(__name__)
scope = {
"headers": [(b"host", b"quart")],
"http_version": "1.1",
"method": "GET",
"scheme": "https",
"path": "/",
"query_string": b"",
}
connection = ASGIHTTPConnection(app, scope)
queue: asyncio.Queue = asyncio.Queue()
queue.put_nowait({"type": "http.request", "body": b"", "more_body": False})
async def receive() -> dict:
# This will block after returning the first and only entry
return await queue.get()
async def send(message: dict) -> None:
pass
# This test fails if a timeout error is raised here
await asyncio.wait_for(connection(receive, send), timeout=1)
示例5: _parse_sdcard_list
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import wait_for [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)
示例6: _connect
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import wait_for [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')
示例7: _get_result
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import wait_for [as 别名]
def _get_result(self, future, start_time, timeout, pending, target_id):
due = self._total_due
if timeout is None:
timeout = self._timeout
if timeout is not None:
due = min(due, start_time + timeout)
# NOTE: We can't try/finally to pop from pending here because
# the event loop needs to get back to us, but it might
# dispatch another update before, and in that case a
# response could be set twice. So responses must be
# cleared when their futures are set to a result.
return asyncio.wait_for(
future,
timeout=None if due == float('inf') else due - time.time(),
loop=self._client.loop
)
示例8: test_create_no_minsize
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import wait_for [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
示例9: test_select_and_create
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import wait_for [as 别名]
def test_select_and_create(create_pool, server):
# trying to model situation when select and acquire
# called simultaneously
# but acquire freezes on _wait_select and
# then continues with proper db
# TODO: refactor this test as there's no _wait_select any more.
with async_timeout.timeout(10):
pool = await create_pool(
server.tcp_address,
minsize=1, db=0,
)
db = 0
while True:
db = (db + 1) & 1
_, conn = await asyncio.gather(pool.select(db),
pool.acquire())
assert pool.db == db
pool.release(conn)
if conn.db == db:
break
# await asyncio.wait_for(test(), 3, loop=loop)
示例10: wait_for_iterator
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import wait_for [as 别名]
def wait_for_iterator(self, connection_observer, connection_observer_future):
"""
Version of wait_for() intended to be used by Python3 to implement awaitable object.
Note: we don't have timeout parameter here. If you want to await with timeout please do use asyncio machinery.
For ex.: await asyncio.wait_for(connection_observer, timeout=10)
:param connection_observer: The one we are awaiting for.
:param connection_observer_future: Future of connection-observer returned from submit().
:return: iterator
"""
self.logger.debug("go foreground: {!r}".format(connection_observer))
# assuming that connection_observer.start() / runner.submit(connection_observer)
# has already scheduled future via asyncio.ensure_future
assert asyncio.futures.isfuture(connection_observer_future)
return connection_observer_future.__iter__()
# Note: even if code is so simple we can't move it inside ConnectionObserver.__await__() since different runners
# may provide different iterator implementing awaitable
# Here we know, connection_observer_future is asyncio.Future (precisely asyncio.tasks.Task)
# and we know it has __await__() method.
示例11: open
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import wait_for [as 别名]
def open(self):
"""Open TCP connection."""
self._debug('connecting to {}'.format(self))
# If a task is canceled while it is waiting for another concurrent operation,
# the task is notified of its cancellation by having a CancelledError exception
# raised at the point where it is waiting
try:
self._stream_reader, self._stream_writer = await asyncio.open_connection(host=self.host, port=self.port)
# self._stream_reader, self._stream_writer = await asyncio.wait_for(asyncio.open_connection(host=self.host, port=self.port), timeout=10)
except asyncio.CancelledError as err:
self._debug("CancelledError while awaiting for open_connection({}), err: {}".format(self, err))
# TODO: stop child task of asyncio.open_connection
raise
else:
self.connection_lost = asyncio.Future() # delayed to be created in same loop as open()
asyncio.ensure_future(self.forward_connection_read_data())
self._debug('connection {} is open'.format(self))
示例12: test_can_receive_binary_data_from_connection
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import wait_for [as 别名]
def test_can_receive_binary_data_from_connection(tcp_connection_class,
integration_tcp_server_and_pipe):
from moler.threaded_moler_connection import ThreadedMolerConnection
(tcp_server, tcp_server_pipe) = integration_tcp_server_and_pipe
received_data = bytearray()
receiver_called = asyncio.Event()
def receiver(data, time_recv):
received_data.extend(data)
receiver_called.set()
moler_conn = ThreadedMolerConnection() # no decoder, just pass bytes 1:1
moler_conn.subscribe(receiver) # build forwarding path
connection = tcp_connection_class(moler_connection=moler_conn, port=tcp_server.port, host=tcp_server.host)
async with connection: # TODO: async with connection.open():
time.sleep(0.1) # otherwise we have race between server's pipe and from-client-connection
tcp_server_pipe.send(("send async msg", {'msg': b'data to read'}))
await asyncio.wait_for(receiver_called.wait(), timeout=0.5)
assert b'data to read' == received_data
# TODO: tests for error cases raising Exceptions
# --------------------------- resources ---------------------------
示例13: __connect
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import wait_for [as 别名]
def __connect(self):
self.__check_closed()
if self.connected:
return
try:
self.logger.debug("Opening connection to %s:%d", self.host, self.port)
future = asyncio.open_connection(self.host, self.port, loop=self.__loop)
self.__reader, self.__writer = await asyncio.wait_for(
future, timeout=self.connect_timeout, loop=self.__loop
)
await asyncio.wait_for(self.__connect_request_response(), timeout=self.request_timeout, loop=self.__loop)
self.logger.debug("Socket connected successfully. Starting read loop.")
self.connected = True
self.__loop.create_task(self.__read_loop())
except ConnectionError as e:
self.logger.error("Connection error while connecting to server: %s", e)
raise
示例14: setUp
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import wait_for [as 别名]
def setUp(self):
setup_mock_web_api_server(self)
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
task = asyncio.ensure_future(self.mock_server(), loop=self.loop)
self.loop.run_until_complete(asyncio.wait_for(task, 0.1))
self.client = slack.RTMClient(
token="xoxb-valid",
base_url="http://localhost:8765",
auto_reconnect=False,
run_async=False,
)
self.client._web_client = slack.WebClient(
token="xoxb-valid",
base_url="http://localhost:8888",
run_async=False,
)
示例15: wait
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import wait_for [as 别名]
def wait(self, timeout=None):
deadline = Deadline(timeout)
barrier_lifted = self.client.wait_for_events(
[WatchEvent.DELETED], self.path
)
exists = await self.client.exists(path=self.path, watch=True)
if not exists:
return
try:
if not deadline.is_indefinite:
await asyncio.wait_for(barrier_lifted, deadline.timeout)
else:
await barrier_lifted
except asyncio.TimeoutError:
raise exc.TimeoutError