本文整理匯總了Python中typing.Awaitable方法的典型用法代碼示例。如果您正苦於以下問題:Python typing.Awaitable方法的具體用法?Python typing.Awaitable怎麽用?Python typing.Awaitable使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類typing
的用法示例。
在下文中一共展示了typing.Awaitable方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: execute
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Awaitable [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
示例2: sync_with_context
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Awaitable [as 別名]
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
示例3: receive_activity_internal
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Awaitable [as 別名]
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
示例4: test_middleware_set_receive_activity_internal
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Awaitable [as 別名]
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)
示例5: respond
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Awaitable [as 別名]
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)
示例6: wait_first
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Awaitable [as 別名]
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)
示例7: run_daemon_task
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Awaitable [as 別名]
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())
示例8: resolve
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Awaitable [as 別名]
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()
示例9: wait
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Awaitable [as 別名]
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
示例10: headers_received
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Awaitable [as 別名]
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)
示例11: handle_stream
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Awaitable [as 別名]
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()
示例12: create_session
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Awaitable [as 別名]
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,
)
示例13: __init__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Awaitable [as 別名]
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 {}
示例14: new_ensure_async
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Awaitable [as 別名]
def new_ensure_async( # type: ignore
self, func: Callable[..., Any]
) -> Callable[..., Awaitable[Any]]:
if is_coroutine_function(func):
return func
else:
return asyncio.coroutine(func)
示例15: __init__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Awaitable [as 別名]
def __init__(
self,
required_endorsements: List[str] = None,
claims_validator: Callable[[List[Dict]], Awaitable] = None,
):
self.required_endorsements = required_endorsements or []
self.claims_validator = claims_validator