本文整理汇总了Python中asyncio.run_coroutine_threadsafe方法的典型用法代码示例。如果您正苦于以下问题:Python asyncio.run_coroutine_threadsafe方法的具体用法?Python asyncio.run_coroutine_threadsafe怎么用?Python asyncio.run_coroutine_threadsafe使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类asyncio
的用法示例。
在下文中一共展示了asyncio.run_coroutine_threadsafe方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _emit
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run_coroutine_threadsafe [as 别名]
def _emit(self, record: logging.LogRecord) -> None:
# JSON conversion based on Marsel Mavletkulov's json-log-formatter (MIT license)
# https://github.com/marselester/json-log-formatter
content = {
name: value
for name, value in record.__dict__.items()
if name not in EXCLUDE_ATTRS
}
content["id"] = str(record.relativeCreated)
content["msg"] = record.getMessage()
content["time"] = datetime.fromtimestamp(record.created)
if record.exc_info:
content["exc_info"] = self.formatter.formatException(record.exc_info)
for name, value in content.items():
if isinstance(value, datetime):
content[name] = value.astimezone().isoformat()
asyncio.run_coroutine_threadsafe(self.send(content), loop=self.loop)
self.lines.append(content)
示例2: run_async_coroutine
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run_coroutine_threadsafe [as 别名]
def run_async_coroutine(self, coroutine_to_run, timeout):
"""Start coroutine in dedicated thread and await its result with timeout"""
start_time = time.time()
coro_future = self.start_async_coroutine(coroutine_to_run)
# run_coroutine_threadsafe returns future as concurrent.futures.Future() and not asyncio.Future
# so, we can await it with timeout inside current thread
try:
coro_result = coro_future.result(timeout=timeout)
self.logger.debug("scheduled {} returned {}".format(coroutine_to_run, coro_result))
return coro_result
except concurrent.futures.TimeoutError:
passed = time.time() - start_time
raise MolerTimeout(timeout=timeout,
kind="run_async_coroutine({})".format(coroutine_to_run),
passed_time=passed)
except concurrent.futures.CancelledError:
raise
示例3: block_check
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run_coroutine_threadsafe [as 别名]
def block_check(loop):
while True:
try:
time.sleep(1)
future = asyncio.run_coroutine_threadsafe(asyncio.sleep(0), loop)
blocked_for = 0
while True:
try:
future.result(1)
break
except asyncio.TimeoutError:
blocked_for += 1
task = asyncio.current_task(loop)
buffer = io.StringIO()
task.print_stack(file=buffer)
buffer.seek(0)
log.warning("Event loop blocked for longer than %d seconds (%s)\n%s\n%s" % (
blocked_for,
str(task),
str(last_commands),
buffer.read()
))
except Exception:
pass
示例4: __handler_get_tx_by_address
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run_coroutine_threadsafe [as 别名]
def __handler_get_tx_by_address(self, request, context):
"""Get Transaction by address
:param request:
:param context:
:return:
"""
params = json.loads(request.meta)
address = params.pop('address', None)
index = params.pop('index', None)
if address is None or index is None: # or params:
return loopchain_pb2.Message(code=message_code.Response.fail_illegal_params)
channel_stub = StubCollection().channel_stubs[request.channel]
future = asyncio.run_coroutine_threadsafe(
channel_stub.async_task().get_tx_by_address(address, index),
self.peer_service.inner_service.loop
)
tx_list, next_index = future.result()
tx_list_dumped = json.dumps(tx_list).encode(encoding=conf.PEER_DATA_ENCODING)
return loopchain_pb2.Message(code=message_code.Response.success,
meta=str(next_index),
object=tx_list_dumped)
示例5: __get_status_cache
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run_coroutine_threadsafe [as 别名]
def __get_status_cache(self, channel_name, time_in_seconds):
"""Cache status data.
:param channel_name:
:param time_in_seconds: An essential parameter for the `LRU cache` even if not used.
:return:
"""
try:
channel_stub = StubCollection().channel_stubs[channel_name]
except KeyError:
raise ChannelStatusError(f"Invalid channel({channel_name})")
if self.__status_cache is None:
self.__status_cache = channel_stub.sync_task().get_status()
else:
future = asyncio.run_coroutine_threadsafe(
channel_stub.async_task().get_status(),
self.peer_service.inner_service.loop)
future.add_done_callback(self.__set_status_cache)
return self.__status_cache
示例6: Stop
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run_coroutine_threadsafe [as 别名]
def Stop(self, request, context):
"""Peer를 중지시킨다
:param request: 중지요청
:param context:
:return: 중지결과
"""
if request is not None:
utils.logger.info('Peer will stop... by: ' + request.reason)
try:
for channel_name in conf.CHANNEL_OPTION:
channel_stub = StubCollection().channel_stubs[channel_name]
asyncio.run_coroutine_threadsafe(channel_stub.async_task().stop(), self.peer_service.inner_service.loop)
self.peer_service.p2p_server_stop()
except Exception as e:
utils.logger.debug("Score Service Already stop by other reason. %s", e)
return loopchain_pb2.StopReply(status="0")
示例7: CreateTx
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run_coroutine_threadsafe [as 别名]
def CreateTx(self, request, context):
"""make tx by client request and broadcast it to the network
:param request:
:param context:
:return:
"""
channel_name = request.channel or conf.LOOPCHAIN_DEFAULT_CHANNEL
utils.logger.info(f"peer_outer_service::CreateTx request({request.data}), channel({channel_name})")
channel_stub = StubCollection().channel_stubs[channel_name]
result_hash = asyncio.run_coroutine_threadsafe(
channel_stub.async_task().create_tx(request.data),
self.peer_service.inner_service.loop
).result()
return loopchain_pb2.CreateTxReply(
response_code=message_code.Response.success,
tx_hash=result_hash,
more_info='')
示例8: GetPrecommitBlock
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run_coroutine_threadsafe [as 别名]
def GetPrecommitBlock(self, request, context):
"""Return the precommit bock.
:param request:
:param context:
:return: loopchain.proto 의 PrecommitBlockReply 참고,
"""
channel_name = conf.LOOPCHAIN_DEFAULT_CHANNEL if request.channel == '' else request.channel
channel_stub = StubCollection().channel_stubs[channel_name]
future = asyncio.run_coroutine_threadsafe(
channel_stub.async_task().get_precommit_block(last_block_height=request.last_block_height),
self.peer_service.inner_service.loop
)
response_code, response_message, block = future.result()
return loopchain_pb2.PrecommitBlockReply(
response_code=response_code, response_message=response_message, block=block)
示例9: GetInvokeResult
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run_coroutine_threadsafe [as 别名]
def GetInvokeResult(self, request, context):
"""get invoke result by tx_hash
:param request: request.tx_hash = tx_hash
:param context:
:return: verify result
"""
channel_name = conf.LOOPCHAIN_DEFAULT_CHANNEL if request.channel == '' else request.channel
utils.logger.debug(f"peer_outer_service:GetInvokeResult in channel({channel_name})")
channel_stub = StubCollection().channel_stubs[channel_name]
future = asyncio.run_coroutine_threadsafe(
channel_stub.async_task().get_invoke_result(request.tx_hash),
self.peer_service.inner_service.loop
)
response_code, result = future.result()
return loopchain_pb2.GetInvokeResultReply(response_code=response_code, result=result)
示例10: AnnounceUnconfirmedBlock
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run_coroutine_threadsafe [as 别名]
def AnnounceUnconfirmedBlock(self, request, context):
"""Send the UnconfirmedBlock includes collected transactions to reps and request to verify it.
:param request:
:param context:
:return:
"""
channel_name = conf.LOOPCHAIN_DEFAULT_CHANNEL if request.channel == '' else request.channel
channel_stub = StubCollection().channel_stubs[channel_name]
try:
round_ = request.round_
except AttributeError:
round_ = 0
asyncio.run_coroutine_threadsafe(
channel_stub.async_task().announce_unconfirmed_block(request.block, round_),
self.peer_service.inner_service.loop
)
return loopchain_pb2.CommonReply(response_code=message_code.Response.success, message="success")
示例11: setup
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run_coroutine_threadsafe [as 别名]
def setup(hass, config):
if (any(conf[CONF_TIME_AS] in (TZ_DEVICE_UTC, TZ_DEVICE_LOCAL)
for conf in (config.get(DT_DOMAIN) or [])
if conf[CONF_PLATFORM] == DOMAIN)):
pkg = config[DOMAIN][CONF_TZ_FINDER]
try:
asyncio.run_coroutine_threadsafe(
async_process_requirements(
hass, '{}.{}'.format(DOMAIN, DT_DOMAIN), [pkg]),
hass.loop
).result()
except RequirementsNotFound:
_LOGGER.debug('Process requirements failed: %s', pkg)
return False
else:
_LOGGER.debug('Process requirements suceeded: %s', pkg)
if pkg.split('==')[0].strip().endswith('L'):
from timezonefinderL import TimezoneFinder
else:
from timezonefinder import TimezoneFinder
hass.data[DOMAIN] = TimezoneFinder()
return True
示例12: init_drivers
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run_coroutine_threadsafe [as 别名]
def init_drivers():
"""
bring up all the drivers
this function should be called by UMRManager
:return:
"""
config = UMRConfig.config.Driver
for driver_name, driver_config in config.items():
if driver_config.Base not in driver_class_lookup_table:
logger.error(f'Base driver "{driver_config.Base}" not found')
exit(-1)
driver: BaseDriverMixin = driver_class_lookup_table[driver_config.Base](driver_name)
driver.start()
driver_lookup_table[driver_name] = driver
loop = asyncio.get_event_loop()
for driver_name in config.keys():
asyncio.run_coroutine_threadsafe(__post_init(driver_name), loop)
示例13: handle_message
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run_coroutine_threadsafe [as 别名]
def handle_message(self, timestamp, source, groupID, message, attachments):
""" Handle Signal message. It should be a command """
logger.debug("Received Message {} {} {} {} {}".format(
timestamp, message, groupID, message, attachments))
if source in cfg.SIGNAL_CONTACTS:
future = asyncio.run_coroutine_threadsafe(self.handle_command(message), self.alarm.work_loop)
ret = future.result(10)
m = "Signal {} : {}".format(source, ret)
logger.info(m)
else:
m = "Signal {} (UNK): {}".format(source, message)
logger.warning(m)
self.send_message(m, EventLevel.INFO)
ps.sendNotification(Notification(sender=self.name, message=m, level=EventLevel.INFO))
示例14: handle_message
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run_coroutine_threadsafe [as 别名]
def handle_message(self, timestamp: str, source: str, message: str) -> None:
""" Handle GSM message. It should be a command """
logger.debug("Received: {} {} {}".format(
timestamp, source, message))
if source in cfg.GSM_CONTACTS:
future = asyncio.run_coroutine_threadsafe(self.handle_command(message), self.alarm.work_loop)
ret = future.result(10)
m = "GSM {}: {}".format(source, ret)
logger.info(m)
else:
m = "GSM {} (UNK): {}".format(source, message)
logger.warning(m)
self.send_message(m, EventLevel.INFO)
ps.sendNotification(Notification(sender=self.name, message=m, level=EventLevel.INFO))
示例15: main
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import run_coroutine_threadsafe [as 别名]
def main(self):
print('start')
async_q = self._queue.async_q
main_loop = asyncio.get_event_loop()
while not (self._stopped and async_q.empty()):
try:
event = self.queue.get_nowait()
except asyncio.QueueEmpty:
pass
else:
asyncio.run_coroutine_threadsafe(
self.event_hadler(event),
main_loop
)
async_q.task_done()
await asyncio.sleep(0.0001)