Python typing.Awaitable() Examples
The following are 30
code examples of typing.Awaitable().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
typing
, or try the search function
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: test_middleware_set.py From botbuilder-python with MIT License | 6 votes |
def test_middleware_set_receive_activity_internal(self): class PrintMiddleware: async def on_turn(self, context_or_string, next_middleware): print("PrintMiddleware says: %s." % context_or_string) return next_middleware class ModifyInputMiddleware(Middleware): async def on_turn( self, context: TurnContext, logic: Callable[[TurnContext], Awaitable] ): context = "Hello" print(context) print("Here is the current context_or_string: %s" % context) return logic async def request_handler(context_or_string): assert context_or_string == "Hello" middleware_set = MiddlewareSet().use(PrintMiddleware()) middleware_set.use(ModifyInputMiddleware()) await middleware_set.receive_activity_internal("Bye", request_handler)
Example #2
Source File: locks.py From teleport with Apache License 2.0 | 6 votes |
def wait(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[None]: """Block until the internal flag is true. Returns an awaitable, which raises `tornado.util.TimeoutError` after a timeout. """ fut = Future() # type: Future[None] if self._value: fut.set_result(None) return fut self._waiters.add(fut) fut.add_done_callback(lambda fut: self._waiters.remove(fut)) if timeout is None: return fut else: timeout_fut = gen.with_timeout( timeout, fut, quiet_exceptions=(CancelledError,) ) # This is a slightly clumsy workaround for the fact that # gen.with_timeout doesn't cancel its futures. Cancelling # fut will remove it from the waiters list. timeout_fut.add_done_callback( lambda tf: fut.cancel() if not fut.done() else None ) return timeout_fut
Example #3
Source File: locks.py From teleport with Apache License 2.0 | 6 votes |
def wait(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[bool]: """Wait for `.notify`. Returns a `.Future` that resolves ``True`` if the condition is notified, or ``False`` after a timeout. """ waiter = Future() # type: Future[bool] self._waiters.append(waiter) if timeout: def on_timeout() -> None: if not waiter.done(): future_set_result_unless_cancelled(waiter, False) self._garbage_collect() io_loop = ioloop.IOLoop.current() timeout_handle = io_loop.add_timeout(timeout, on_timeout) waiter.add_done_callback(lambda _: io_loop.remove_timeout(timeout_handle)) return waiter
Example #4
Source File: netutil.py From teleport with Apache License 2.0 | 6 votes |
def resolve( self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC ) -> Awaitable[List[Tuple[int, Any]]]: """Resolves an address. The ``host`` argument is a string which may be a hostname or a literal IP address. Returns a `.Future` whose result is a list of (family, address) pairs, where address is a tuple suitable to pass to `socket.connect <socket.socket.connect>` (i.e. a ``(host, port)`` pair for IPv4; additional fields may be present for IPv6). If a ``callback`` is passed, it will be run with the result as an argument when it is complete. :raises IOError: if the address cannot be resolved. .. versionchanged:: 4.4 Standardized all implementations to raise `IOError`. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ raise NotImplementedError()
Example #5
Source File: _synchronise.py From quart with MIT License | 6 votes |
def sync_with_context(future: Awaitable) -> Any: context = None if _request_ctx_stack.top is not None: context = _request_ctx_stack.top.copy() elif _websocket_ctx_stack.top is not None: context = _websocket_ctx_stack.top.copy() elif _app_ctx_stack.top is not None: context = _app_ctx_stack.top.copy() async def context_wrapper() -> Any: if context is not None: async with context: return await future else: return await future return asyncio.get_event_loop().sync_wait(context_wrapper()) # type: ignore
Example #6
Source File: routing.py From teleport with Apache License 2.0 | 6 votes |
def headers_received( self, start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine], headers: httputil.HTTPHeaders, ) -> Optional[Awaitable[None]]: assert isinstance(start_line, httputil.RequestStartLine) request = httputil.HTTPServerRequest( connection=self.request_conn, server_connection=self.server_conn, start_line=start_line, headers=headers, ) self.delegate = self.router.find_handler(request) if self.delegate is None: app_log.debug( "Delegate for %s %s request not found", start_line.method, start_line.path, ) self.delegate = _DefaultMessageDelegate(self.request_conn) return self.delegate.headers_received(start_line, headers)
Example #7
Source File: middleware_set.py From botbuilder-python with MIT License | 6 votes |
def receive_activity_internal( self, context: TurnContext, callback: Callable[[TurnContext], Awaitable], next_middleware_index: int = 0, ): if next_middleware_index == len(self._middleware): if callback is not None: return await callback(context) return None next_middleware = self._middleware[next_middleware_index] async def call_next_middleware(): return await self.receive_activity_internal( context, callback, next_middleware_index + 1 ) try: return await next_middleware.on_turn(context, call_next_middleware) except Exception as error: raise error
Example #8
Source File: timer_service.py From loopchain with Apache License 2.0 | 6 votes |
def __init__(self, **kwargs): """initial function :param target: target of timer :param duration: duration for checking timeout :param start_time: start time of timer :param is_repeat: if true, the timer runs repeatedly :param callback: callback function after timeout or normal case :param kwargs: parameters for callback function """ self.target = kwargs.get("target") self.duration = kwargs.get("duration") self.is_run_at_start: bool = kwargs.get("is_run_at_start", False) self._is_repeat: bool = kwargs.get("is_repeat", False) # only works If is_repeat=True. 0 means no timeout. self._repeat_timeout: int = kwargs.get("repeat_timeout", 0) self.__start_time = time.time() self.__repeat_start_time = self.__start_time self.__callback: Union[Callable, Awaitable] = kwargs.get("callback", None) self.__kwargs = kwargs.get("callback_kwargs") or {}
Example #9
Source File: matrix.py From maubot with GNU Affero General Public License v3.0 | 6 votes |
def respond(self, content: Union[str, MessageEventContent], event_type: EventType = EventType.ROOM_MESSAGE, markdown: bool = True, allow_html: bool = False, reply: Union[bool, str] = False, edits: Optional[Union[EventID, MessageEvent]] = None) -> Awaitable[EventID]: if isinstance(content, str): content = TextMessageEventContent(msgtype=MessageType.NOTICE, body=content) if allow_html or markdown: content.format = Format.HTML content.body, content.formatted_body = parse_formatted(content.body, render_markdown=markdown, allow_html=allow_html) if edits: content.set_edit(edits) elif reply: if reply != "force" and self.disable_reply: content.body = f"{self.sender}: {content.body}" fmt_body = content.formatted_body or escape(content.body).replace("\n", "<br>") content.formatted_body = (f'<a href="https://matrix.to/#/{self.sender}">' f'{self.sender}' f'</a>: {fmt_body}') else: content.set_reply(self) return self.client.send_message_event(self.room_id, event_type, content)
Example #10
Source File: base.py From aries-cloudagent-python with Apache License 2.0 | 6 votes |
def create_session( self, *, accept_undelivered: bool = False, can_respond: bool = False, client_info: dict = None, wire_format: BaseWireFormat = None, ) -> Awaitable[InboundSession]: """ Create a new inbound session. Args: accept_undelivered: Flag for accepting undelivered messages can_respond: Flag indicating that the transport can send responses client_info: Request-specific client information wire_format: Optionally override the session wire format """ return self._create_session( accept_undelivered=accept_undelivered, can_respond=can_respond, client_info=client_info, wire_format=wire_format or self.wire_format, transport_type=self.scheme, )
Example #11
Source File: tcpserver.py From opendevops with GNU General Public License v3.0 | 6 votes |
def handle_stream( self, stream: IOStream, address: tuple ) -> Optional[Awaitable[None]]: """Override to handle a new `.IOStream` from an incoming connection. This method may be a coroutine; if so any exceptions it raises asynchronously will be logged. Accepting of incoming connections will not be blocked by this coroutine. If this `TCPServer` is configured for SSL, ``handle_stream`` may be called before the SSL handshake has completed. Use `.SSLIOStream.wait_for_handshake` if you need to verify the client's certificate or use NPN/ALPN. .. versionchanged:: 4.2 Added the option for this method to be a coroutine. """ raise NotImplementedError()
Example #12
Source File: cancellable.py From pyquarkchain with MIT License | 6 votes |
def wait_first( self, *awaitables: Awaitable[_TReturn], token: CancelToken = None, timeout: float = None ) -> _TReturn: """ Wait for the first awaitable to complete, unless we timeout or the token chain is triggered. The given token is chained with this service's token, so triggering either will cancel this. Returns the result of the first one to complete. Raises TimeoutError if we timeout or OperationCancelled if the token chain is triggered. All pending futures are cancelled before returning. """ if token is None: token_chain = self.cancel_token else: token_chain = token.chain(self.cancel_token) return await token_chain.cancellable_wait(*awaitables, timeout=timeout)
Example #13
Source File: routing.py From opendevops with GNU General Public License v3.0 | 6 votes |
def headers_received( self, start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine], headers: httputil.HTTPHeaders, ) -> Optional[Awaitable[None]]: assert isinstance(start_line, httputil.RequestStartLine) request = httputil.HTTPServerRequest( connection=self.request_conn, server_connection=self.server_conn, start_line=start_line, headers=headers, ) self.delegate = self.router.find_handler(request) if self.delegate is None: app_log.debug( "Delegate for %s %s request not found", start_line.method, start_line.path, ) self.delegate = _DefaultMessageDelegate(self.request_conn) return self.delegate.headers_received(start_line, headers)
Example #14
Source File: service.py From pyquarkchain with MIT License | 6 votes |
def run_daemon_task(self, awaitable: Awaitable[Any]) -> None: """Run the given awaitable in the background. Like :meth:`run_task` but if the task ends without cancelling, then this this service will terminate as well. """ @functools.wraps(awaitable) # type: ignore async def _run_daemon_task_wrapper() -> None: try: await awaitable finally: if not self.is_cancelled: # self.logger.debug( # "%s finished while %s is still running, terminating as well" # % (awaitable, self) # ) self.cancel_token.trigger() self.run_task(_run_daemon_task_wrapper())
Example #15
Source File: locks.py From opendevops with GNU General Public License v3.0 | 6 votes |
def wait(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[None]: """Block until the internal flag is true. Returns an awaitable, which raises `tornado.util.TimeoutError` after a timeout. """ fut = Future() # type: Future[None] if self._value: fut.set_result(None) return fut self._waiters.add(fut) fut.add_done_callback(lambda fut: self._waiters.remove(fut)) if timeout is None: return fut else: timeout_fut = gen.with_timeout( timeout, fut, quiet_exceptions=(CancelledError,) ) # This is a slightly clumsy workaround for the fact that # gen.with_timeout doesn't cancel its futures. Cancelling # fut will remove it from the waiters list. timeout_fut.add_done_callback( lambda tf: fut.cancel() if not fut.done() else None ) return timeout_fut
Example #16
Source File: locks.py From opendevops with GNU General Public License v3.0 | 6 votes |
def wait(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[bool]: """Wait for `.notify`. Returns a `.Future` that resolves ``True`` if the condition is notified, or ``False`` after a timeout. """ waiter = Future() # type: Future[bool] self._waiters.append(waiter) if timeout: def on_timeout() -> None: if not waiter.done(): future_set_result_unless_cancelled(waiter, False) self._garbage_collect() io_loop = ioloop.IOLoop.current() timeout_handle = io_loop.add_timeout(timeout, on_timeout) waiter.add_done_callback(lambda _: io_loop.remove_timeout(timeout_handle)) return waiter
Example #17
Source File: netutil.py From opendevops with GNU General Public License v3.0 | 6 votes |
def resolve( self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC ) -> Awaitable[List[Tuple[int, Any]]]: """Resolves an address. The ``host`` argument is a string which may be a hostname or a literal IP address. Returns a `.Future` whose result is a list of (family, address) pairs, where address is a tuple suitable to pass to `socket.connect <socket.socket.connect>` (i.e. a ``(host, port)`` pair for IPv4; additional fields may be present for IPv6). If a ``callback`` is passed, it will be run with the result as an argument when it is complete. :raises IOError: if the address cannot be resolved. .. versionchanged:: 4.4 Standardized all implementations to raise `IOError`. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ raise NotImplementedError()
Example #18
Source File: queues.py From teleport with Apache License 2.0 | 5 votes |
def __anext__(self) -> Awaitable[_T]: return self.q.get()
Example #19
Source File: httpserver.py From teleport with Apache License 2.0 | 5 votes |
def data_received(self, chunk: bytes) -> Optional[Awaitable[None]]: return self.delegate.data_received(chunk)
Example #20
Source File: http1connection.py From opendevops with GNU General Public License v3.0 | 5 votes |
def headers_received( self, start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine], headers: httputil.HTTPHeaders, ) -> Optional[Awaitable[None]]: if headers.get("Content-Encoding") == "gzip": self._decompressor = GzipDecompressor() # Downstream delegates will only see uncompressed data, # so rename the content-encoding header. # (but note that curl_httpclient doesn't do this). headers.add("X-Consumed-Content-Encoding", headers["Content-Encoding"]) del headers["Content-Encoding"] return self._delegate.headers_received(start_line, headers)
Example #21
Source File: http1connection.py From opendevops with GNU General Public License v3.0 | 5 votes |
def read_response(self, delegate: httputil.HTTPMessageDelegate) -> Awaitable[bool]: """Read a single HTTP response. Typical client-mode usage is to write a request using `write_headers`, `write`, and `finish`, and then call ``read_response``. :arg delegate: a `.HTTPMessageDelegate` Returns a `.Future` that resolves to a bool after the full response has been read. The result is true if the stream is still open. """ if self.params.decompress: delegate = _GzipMessageDelegate(delegate, self.params.chunk_size) return self._read_message(delegate)
Example #22
Source File: asyncio.py From teleport with Apache License 2.0 | 5 votes |
def run_in_executor( self, executor: Optional[concurrent.futures.Executor], func: Callable[..., _T], *args: Any ) -> Awaitable[_T]: return self.asyncio_loop.run_in_executor(executor, func, *args)
Example #23
Source File: locks.py From teleport with Apache License 2.0 | 5 votes |
def acquire( self, timeout: Union[float, datetime.timedelta] = None ) -> Awaitable[_ReleasingContextManager]: """Decrement the counter. Returns an awaitable. Block if the counter is zero and wait for a `.release`. The awaitable raises `.TimeoutError` after the deadline. """ waiter = Future() # type: Future[_ReleasingContextManager] if self._value > 0: self._value -= 1 waiter.set_result(_ReleasingContextManager(self)) else: self._waiters.append(waiter) if timeout: def on_timeout() -> None: if not waiter.done(): waiter.set_exception(gen.TimeoutError()) self._garbage_collect() io_loop = ioloop.IOLoop.current() timeout_handle = io_loop.add_timeout(timeout, on_timeout) waiter.add_done_callback( lambda _: io_loop.remove_timeout(timeout_handle) ) return waiter
Example #24
Source File: locks.py From opendevops with GNU General Public License v3.0 | 5 votes |
def acquire( self, timeout: Union[float, datetime.timedelta] = None ) -> Awaitable[_ReleasingContextManager]: """Attempt to lock. Returns an awaitable. Returns an awaitable, which raises `tornado.util.TimeoutError` after a timeout. """ return self._block.acquire(timeout)
Example #25
Source File: locks.py From opendevops with GNU General Public License v3.0 | 5 votes |
def acquire( self, timeout: Union[float, datetime.timedelta] = None ) -> Awaitable[_ReleasingContextManager]: """Decrement the counter. Returns an awaitable. Block if the counter is zero and wait for a `.release`. The awaitable raises `.TimeoutError` after the deadline. """ waiter = Future() # type: Future[_ReleasingContextManager] if self._value > 0: self._value -= 1 waiter.set_result(_ReleasingContextManager(self)) else: self._waiters.append(waiter) if timeout: def on_timeout() -> None: if not waiter.done(): waiter.set_exception(gen.TimeoutError()) self._garbage_collect() io_loop = ioloop.IOLoop.current() timeout_handle = io_loop.add_timeout(timeout, on_timeout) waiter.add_done_callback( lambda _: io_loop.remove_timeout(timeout_handle) ) return waiter
Example #26
Source File: locks.py From teleport with Apache License 2.0 | 5 votes |
def acquire( self, timeout: Union[float, datetime.timedelta] = None ) -> Awaitable[_ReleasingContextManager]: """Attempt to lock. Returns an awaitable. Returns an awaitable, which raises `tornado.util.TimeoutError` after a timeout. """ return self._block.acquire(timeout)
Example #27
Source File: asyncio.py From opendevops with GNU General Public License v3.0 | 5 votes |
def run_in_executor( self, executor: Optional[concurrent.futures.Executor], func: Callable[..., _T], *args: Any ) -> Awaitable[_T]: return self.asyncio_loop.run_in_executor(executor, func, *args)
Example #28
Source File: netutil.py From opendevops with GNU General Public License v3.0 | 5 votes |
def resolve( self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC ) -> Awaitable[List[Tuple[int, Any]]]: if (host, port, family) in self.mapping: host, port = self.mapping[(host, port, family)] elif (host, port) in self.mapping: host, port = self.mapping[(host, port)] elif host in self.mapping: host = self.mapping[host] return self.resolver.resolve(host, port, family) # These are the keyword arguments to ssl.wrap_socket that must be translated # to their SSLContext equivalents (the other arguments are still passed # to SSLContext.wrap_socket).
Example #29
Source File: httpserver.py From opendevops with GNU General Public License v3.0 | 5 votes |
def data_received(self, chunk: bytes) -> Optional[Awaitable[None]]: self._chunks.append(chunk) return None
Example #30
Source File: websockets.py From python-idex with MIT License | 5 votes |
def create(cls, loop, callback: Callable[[int], Awaitable[str]], api_key): self = IdexSocketManager() self._loop = loop self._callback = callback self._conn = ReconnectingWebsocket(loop, self._recv, api_key=api_key) return self