本文整理匯總了Python中asyncio.wrap_future方法的典型用法代碼示例。如果您正苦於以下問題:Python asyncio.wrap_future方法的具體用法?Python asyncio.wrap_future怎麽用?Python asyncio.wrap_future使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類asyncio
的用法示例。
在下文中一共展示了asyncio.wrap_future方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: run_in_executor
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import wrap_future [as 別名]
def run_in_executor(self, executor, callback, *args):
"""Run callback in executor.
If no executor is provided, the default executor will be used, which defers execution to
a background thread.
"""
self._logger.debug('Running callback {} with args {} in executor'.format(callback, args))
if isinstance(callback, asyncio.Handle):
assert not args
assert not isinstance(callback, asyncio.TimerHandle)
if callback._cancelled:
f = asyncio.Future()
f.set_result(None)
return f
callback, args = callback.callback, callback.args
if executor is None:
self._logger.debug('Using default executor')
executor = self.__default_executor
if executor is None:
self._logger.debug('Creating default executor')
executor = self.__default_executor = QThreadExecutor()
return asyncio.wrap_future(executor.submit(callback, *args))
示例2: _Compute
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import wrap_future [as 別名]
def _Compute(
self,
request: executor_pb2.ComputeRequest,
context: grpc.ServicerContext,
) -> executor_pb2.ComputeResponse:
"""Asynchronous implemention of `Compute`."""
py_typecheck.check_type(request, executor_pb2.ComputeRequest)
try:
value_id = str(request.value_ref.id)
with self._lock:
future_val = asyncio.wrap_future(self._values[value_id])
val = await future_val
result_val = await val.compute()
val_type = val.type_signature
value_proto, _ = executor_service_utils.serialize_value(
result_val, val_type)
return executor_pb2.ComputeResponse(value=value_proto)
except (ValueError, TypeError) as err:
_set_invalid_arg_err(context, err)
return executor_pb2.ComputeResponse()
示例3: get
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import wrap_future [as 別名]
def get(self):
consumer_token = ConsumerToken(
self.authenticator.client_id,
self.authenticator.client_secret,
)
handshaker = Handshaker(
self.authenticator.mw_index_url, consumer_token
)
redirect, request_token = await wrap_future(
self.authenticator.executor.submit(handshaker.initiate)
)
self.set_secure_cookie(
AUTH_REQUEST_COOKIE_NAME,
jsonify(request_token),
expires_days=1,
path=url_path_join(self.base_url, 'hub', 'oauth_callback'),
httponly=True)
self.log.info('oauth redirect: %r', redirect)
self.redirect(redirect)
示例4: run_in_order_threadsafe
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import wrap_future [as 別名]
def run_in_order_threadsafe(awaitables, loop, timeout=0.5, block=True):
""""Given a sequence of awaitables, schedule each threadsafe in order
optionally blocking until completion.
Returns a `concurrent.futures.Future` which can be used to wait on the
result returned from the last awaitable. If `block` is `True` the final
result will be waited on before returning control to the caller.
"""
future = asyncio.run_coroutine_threadsafe(
await_in_order(awaitables, loop, timeout),
loop
)
if block:
if not loop.is_running():
result = loop.run_until_complete(
asyncio.wrap_future(future, loop=loop))
assert result is future.result()
else:
future.result(timeout)
return future
示例5: ask
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import wrap_future [as 別名]
def ask(self, dst, content=None, dst_node=None):
"""Send request and wait response"""
if not dst_node:
dst_node = self.registery.choice_dst_node(dst)
msg = self.registery.create_message(
dst=dst,
is_ask=True,
content=content,
src=self.actor.name,
dst_node=dst_node,
)
if msg.is_local:
future = ThreadFuture()
msg.future = future
if self.actor.is_async:
return asyncio.wrap_future(future)
else:
return future.result()
else:
return self._actor_client.ask(msg)
示例6: watch_build_pods
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import wrap_future [as 別名]
def watch_build_pods(self):
"""Watch build pods
Every build_cleanup_interval:
- delete stopped build pods
- delete running build pods older than build_max_age
"""
while True:
try:
await asyncio.wrap_future(
self.executor.submit(
lambda: Build.cleanup_builds(
self.kube_client,
self.build_namespace,
self.build_max_age,
)
)
)
except Exception:
app_log.exception("Failed to cleanup build pods")
await asyncio.sleep(self.build_cleanup_interval)
示例7: _get_pods
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import wrap_future [as 別名]
def _get_pods(self):
"""Get information about build and user pods"""
app_log.info("Getting pod statistics")
k8s = self.settings["kubernetes_client"]
pool = self.settings["executor"]
get_user_pods = asyncio.wrap_future(
pool.submit(
k8s.list_namespaced_pod,
self.settings["build_namespace"],
label_selector="app=jupyterhub,component=singleuser-server",
)
)
get_build_pods = asyncio.wrap_future(
pool.submit(
k8s.list_namespaced_pod,
self.settings["build_namespace"],
label_selector="component=binderhub-build",
)
)
return await asyncio.gather(get_user_pods, get_build_pods)
示例8: test_fetchall_prevents_sqlite_misuse
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import wrap_future [as 別名]
def test_fetchall_prevents_sqlite_misuse(self):
# test that calling fetchall sufficiently avoids the race
attempts = 0
def executemany_fetchall(query, params):
self.db.executemany(query, params).fetchall()
while attempts < self.max_misuse_attempts:
f1 = asyncio.wrap_future(
self.loop.run_in_executor(
self.executor, executemany_fetchall, "update test1 set val='derp' where id=?",
((str(i),) for i in range(2))
)
)
f2 = asyncio.wrap_future(
self.loop.run_in_executor(
self.executor, executemany_fetchall, "update test2 set val='derp' where id=?",
((str(i),) for i in range(2))
)
)
attempts += 1
await asyncio.gather(f1, f2)
示例9: _await_loopsafe
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import wrap_future [as 別名]
def _await_loopsafe(self, *coros_or_futures):
""" 事件循環安全的異步等待。
Args:
*coros_or_futures: coroutine或future對象列表。
Returns:
返回coros_or_futures的返回結果列表。
"""
current_loop = asyncio.get_running_loop()
loop = self._loop
if loop is None:
loop = current_loop
async def _execute_loop():
with h.enter(self._handlers):
r = await asyncio.gather(*coros_or_futures)
return r
fut = asyncio.run_coroutine_threadsafe(_execute_loop(), loop)
result = await asyncio.wrap_future(fut)
return result
示例10: connect
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import wrap_future [as 別名]
def connect(cls, path: Union[bytes, str], *args, **kwargs):
db = cls()
db.connection = await wrap_future(db.executor.submit(sqlite3.connect, path, *args, **kwargs))
return db
示例11: executescript
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import wrap_future [as 別名]
def executescript(self, script: str) -> Awaitable:
return wrap_future(self.executor.submit(self.connection.executescript, script))
示例12: execute_fetchall
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import wrap_future [as 別名]
def execute_fetchall(self, sql: str, parameters: Iterable = None) -> Awaitable[Iterable[sqlite3.Row]]:
parameters = parameters if parameters is not None else []
def __fetchall(conn: sqlite3.Connection, *args, **kwargs):
return conn.execute(*args, **kwargs).fetchall()
return wrap_future(self.executor.submit(__fetchall, self.connection, sql, parameters))
示例13: run
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import wrap_future [as 別名]
def run(self, fun, *args, **kwargs) -> Awaitable:
return wrap_future(self.executor.submit(self.__run_transaction, fun, *args, **kwargs))
示例14: run_with_foreign_keys_disabled
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import wrap_future [as 別名]
def run_with_foreign_keys_disabled(self, fun, *args, **kwargs) -> Awaitable:
return wrap_future(
self.executor.submit(self.__run_transaction_with_foreign_keys_disabled, fun, *args, **kwargs)
)
示例15: test_submit
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import wrap_future [as 別名]
def test_submit(self):
with warnings.catch_warnings(record=True) as w:
expected = g(10, 9, z=8)
f = self.pool.submit(g, 10, 9, z=8)
actual = loop.run_until_complete(asyncio.wrap_future(f))
self.assertEqual(actual, expected)
self.assertNoWarnings(w)