Asyncio使发出非阻塞请求变得容易
如果你的程序在asyncio中运行
.例如:
async def doit():
task = asyncio.create_task(call_endpoint_async(url, data))
print('cp #1')
await asyncio.sleep(1)
print('is it done?', task.done())
await task
print('now it is done')
但这要求“调用者”也是异步的。在您的例子中,您希望整个asyncio事件循环在后台运行,以便。这可以通过在单独的线程中运行来实现,例如:
pool = concurrent.futures.ThreadPoolExecutor()
# ...
def post(self, request):
fut = pool.submit(asyncio.run, call_endpoint_async(url, data))
print('cp #1')
然而,在这种情况下,使用asyncio不会得到任何结果。既然你正在使用线程,你也可以调用一个同步函数,比如
requests.get()
首先。