本文整理汇总了Python中asyncio.get_running_loop方法的典型用法代码示例。如果您正苦于以下问题:Python asyncio.get_running_loop方法的具体用法?Python asyncio.get_running_loop怎么用?Python asyncio.get_running_loop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类asyncio
的用法示例。
在下文中一共展示了asyncio.get_running_loop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_sync
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_running_loop [as 别名]
def run_sync(func: Callable[..., Any]) -> Callable[..., Coroutine[Any, None, None]]:
"""Ensure that the sync function is run within the event loop.
If the *func* is not a coroutine it will be wrapped such that
it runs in the default executor (use loop.set_default_executor
to change). This ensures that synchronous functions do not
block the event loop.
"""
@wraps(func)
async def _wrapper(*args: Any, **kwargs: Any) -> Any:
loop = asyncio.get_running_loop()
result = await loop.run_in_executor(
None, copy_context().run, partial(func, *args, **kwargs)
)
if isgenerator(result):
return run_sync_iterable(result) # type: ignore
else:
return result
_wrapper._quart_async_wrapper = True # type: ignore
return _wrapper
示例2: run_sync_iterable
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_running_loop [as 别名]
def run_sync_iterable(iterable: Generator[Any, None, None]) -> AsyncGenerator[Any, None]:
async def _gen_wrapper() -> AsyncGenerator[Any, None]:
# Wrap the generator such that each iteration runs
# in the executor. Then rationalise the raised
# errors so that it ends.
def _inner() -> Any:
# https://bugs.python.org/issue26221
# StopIteration errors are swallowed by the
# run_in_exector method
try:
return next(iterable)
except StopIteration:
raise StopAsyncIteration()
loop = asyncio.get_running_loop()
while True:
try:
yield await loop.run_in_executor(None, copy_context().run, _inner)
except StopAsyncIteration:
return
return _gen_wrapper()
示例3: main
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_running_loop [as 别名]
def main():
redis = await aioredis.create_redis_pool('redis://localhost')
ch, = await redis.psubscribe('channel:*')
assert isinstance(ch, aioredis.Channel)
async def reader(channel):
async for ch, message in channel.iter():
print("Got message in channel:", ch, ":", message)
asyncio.get_running_loop().create_task(reader(ch))
await redis.publish('channel:1', 'Hello')
await redis.publish('channel:2', 'World')
redis.close()
await redis.wait_closed()
示例4: main
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_running_loop [as 别名]
def main():
redis = await aioredis.create_redis_pool('redis://localhost')
ch1, ch2 = await redis.subscribe('channel:1', 'channel:2')
assert isinstance(ch1, aioredis.Channel)
assert isinstance(ch2, aioredis.Channel)
async def reader(channel):
async for message in channel.iter():
print("Got message:", message)
asyncio.get_running_loop().create_task(reader(ch1))
asyncio.get_running_loop().create_task(reader(ch2))
await redis.publish('channel:1', 'Hello')
await redis.publish('channel:2', 'World')
redis.close()
await redis.wait_closed()
示例5: __aenter__
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_running_loop [as 别名]
def __aenter__(self):
if self._entered:
raise RuntimeError(
f"TaskGroup {self!r} has been already entered")
self._entered = True
if self._loop is None:
self._loop = asyncio.get_running_loop()
self._parent_task = asyncio.current_task(self._loop)
if self._parent_task is None:
raise RuntimeError(
f'TaskGroup {self!r} cannot determine the parent task')
self._patch_task(self._parent_task)
return self
示例6: connect
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_running_loop [as 别名]
def connect(self, start: int, headers: bytes) -> int:
added = 0
bail = False
loop = asyncio.get_running_loop()
async with self._header_connect_lock:
for height, chunk in self._iterate_chunks(start, headers):
try:
# validate_chunk() is CPU bound and reads previous chunks from file system
await loop.run_in_executor(None, self.validate_chunk, height, chunk)
except InvalidHeader as e:
bail = True
chunk = chunk[:(height-e.height)*self.header_size]
written = 0
if chunk:
self.io.seek(height * self.header_size, os.SEEK_SET)
written = self.io.write(chunk) // self.header_size
self.io.truncate()
# .seek()/.write()/.truncate() might also .flush() when needed
# the goal here is mainly to ensure we're definitely flush()'ing
await loop.run_in_executor(None, self.io.flush)
self._size = None
added += written
if bail:
break
return added
示例7: get_auth_data_login
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_running_loop [as 别名]
def get_auth_data_login(self, cookie_jar, credentials):
code = parse_qs(urlparse(credentials['end_uri']).query)["code"][0]
loop = asyncio.get_running_loop()
s = requests.Session()
url = f"{self.blizzard_oauth_url}/token"
data = {
"grant_type": "authorization_code",
"redirect_uri": REDIRECT_URI,
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"code": code
}
response = await loop.run_in_executor(None, partial(s.post, url, data=data))
response.raise_for_status()
result = response.json()
access_token = result["access_token"]
self.auth_data = WebsiteAuthData(cookie_jar=cookie_jar, access_token=access_token, region=self.region)
return self.auth_data
# NOTE: use user data to present usertag/name to Galaxy, if this token expires and plugin cannot refresh it
# use stored usertag/name if token validation fails, this is temporary solution, as we do not need that
# endpoint for nothing else at this moment
示例8: simulator
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_running_loop [as 别名]
def simulator(request: requests.Request):
token = request.headers.get("Authorization")
if token:
token = token[6:] # Drop 'token '
data = SimulatorSchema(await request.json())
if data["pull_request"]:
loop = asyncio.get_running_loop()
title, summary = await loop.run_in_executor(
None,
functools.partial(
_sync_simulator,
data["mergify.yml"]["pull_request_rules"],
*data["pull_request"],
token=token,
),
)
else:
title, summary = ("The configuration is valid", None)
return responses.JSONResponse(
status_code=200, content={"title": title, "summary": summary}
)
示例9: __init__
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_running_loop [as 别名]
def __init__(
self, session, host, port, ssl_context, site, callback, is_unifi_os=False,
):
"""Create resources for websocket communication."""
self.session = session
self.ssl_context = ssl_context
self.session_handler_callback = callback
if is_unifi_os:
self.url = f"wss://{host}:{port}/proxy/network/wss/s/{site}/events"
else:
self.url = f"wss://{host}:{port}/wss/s/{site}/events"
self._loop = asyncio.get_running_loop()
self._data = None
self._state = None
示例10: start_async_server
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_running_loop [as 别名]
def start_async_server(self):
try:
xmppserverlog.info(
"Starting XMPP Server at {}:{}".format(self.address[0], self.address[1])
)
loop = asyncio.get_running_loop()
self.server = await loop.create_server(
self.xmpp_protocol, host=self.address[0], port=self.address[1]
)
self.server_coro = loop.create_task(self.server.serve_forever())
except PermissionError as e:
xmppserverlog.error(e.strerror)
asyncio.create_task(bumper.shutdown())
pass
except asyncio.CancelledError:
pass
except Exception as e:
xmppserverlog.exception("{}".format(e))
asyncio.create_task(bumper.shutdown())
示例11: _signal_handling
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_running_loop [as 别名]
def _signal_handling(logger: logging.Logger, client: naz.Client) -> None:
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = asyncio.get_event_loop()
try:
for _signal in [signal.SIGHUP, signal.SIGQUIT, signal.SIGTERM]:
loop.add_signal_handler(
_signal,
functools.partial(
asyncio.ensure_future,
_handle_termination_signal(logger=logger, _signal=_signal, client=client),
),
)
except ValueError as e:
logger.log(
logging.DEBUG,
{
"event": "naz.cli.signals",
"stage": "end",
"state": "this OS does not support the said signal",
"error": str(e),
},
)
示例12: async_turn_off
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_running_loop [as 别名]
def async_turn_off(self):
_LOGGER.debug("Light " + self._friendly_name + " turning off.")
url = 'https://api.wyzecam.com/app/v2/device/set_property'
payload = {
'phone_id': self._api._device_id,
'access_token': self._api._access_token,
'device_model': self._device_model,
'ts': '1575948896791',
'sc': '01dd431d098546f9baf5233724fa2ee2',
'sv': '107693eb44244a948901572ddab807eb',
'device_mac': self._device_mac,
'pvalue': "0",
'pid': 'P3',
'app_ver': 'com.hualai.WyzeCam___2.6.62'
}
loop = asyncio.get_running_loop()
loop.create_task(self._api.async_do_request(url, payload))
self._state = False
self._just_changed_state = True
示例13: async_turn_on
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_running_loop [as 别名]
def async_turn_on(self):
_LOGGER.debug("Switch " + self._friendly_name + " turning on.")
url = 'https://api.wyzecam.com/app/v2/device/set_property'
payload = {
'phone_id': self._api._device_id,
'access_token': self._api._access_token,
'device_model': self._device_model,
'ts': '1575948896791',
'sc': '01dd431d098546f9baf5233724fa2ee2',
'sv': '107693eb44244a948901572ddab807eb',
'device_mac': self._device_mac,
'pvalue': "1",
'pid': 'P3',
'app_ver': 'com.hualai.WyzeCam___2.6.62'
}
loop = asyncio.get_running_loop()
loop.create_task(self._api.async_do_request(url, payload))
self._state = True
self._just_changed_state = True
示例14: start
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_running_loop [as 别名]
def start(self):
self.log.info("Starting Daemon Server")
def master_close_cb():
asyncio.ensure_future(self.stop())
try:
asyncio.get_running_loop().add_signal_handler(
signal.SIGINT, master_close_cb
)
asyncio.get_running_loop().add_signal_handler(
signal.SIGTERM, master_close_cb
)
except NotImplementedError:
self.log.info("Not implemented")
self.websocket_server = await websockets.serve(
self.safe_handle, "localhost", 55400
)
self.log.info("Waiting Daemon WebSocketServer closure")
print("Daemon server started", flush=True)
await self.websocket_server.wait_closed()
self.log.info("Daemon WebSocketServer closed")
示例15: pre_validate_blocks_multiprocessing
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import get_running_loop [as 别名]
def pre_validate_blocks_multiprocessing(
self, blocks: List[FullBlock]
) -> List[Tuple[bool, Optional[bytes32]]]:
futures = []
# Pool of workers to validate blocks concurrently
for block in blocks:
if self._shut_down:
return [(False, None) for _ in range(len(blocks))]
futures.append(
asyncio.get_running_loop().run_in_executor(
self.pool,
pre_validate_finished_block_header,
self.constants,
bytes(block),
)
)
results = await asyncio.gather(*futures)
for i, (val, pos) in enumerate(results):
if pos is not None:
pos = bytes32(pos)
results[i] = val, pos
return results