我试图使用asyncio调用一个REST API async,但我一直收到错误"coroutine was never awaited“,这是我理解的。但是我想要这样的行为,我希望我的函数只通过发布而不是等待结果来结束。以下是我的代码
async def callCoroutine:
#call a REST API
def lambda_handler(event, context):
loop = asyncio.get_event_loop()
task = loop.create_task(callCoroutine(data))
return有人能帮帮忙吗?
发布于 2018-08-22 17:01:59
在您的示例中,主线程正在同步运行。因此,您需要使用asyncio.run_coroutine_threadsafe在另一个线程中运行异步循环。
import asyncio
import threading
# Run asyncio loop in other thread
loop = asyncio.new_event_loop()
threading.Thread(target=loop.run_forever).start()
async def call_coroutine(data):
# call a REST API
return
def lambda_handler(event, context):
# Run the coroutine on the loop of other thread
future = asyncio.run_coroutine_threadsafe(call_coroutine(data), loop)
# If need to get result:
result = future.result() # This will block the main thread
do_something_else()
return
# If need to stop the asyncio loop
loop.call_soon_threadsafe(loop.stop)https://stackoverflow.com/questions/51674786
复制相似问题