我想在 Python 3.7 中执行非阻塞 http 请求。我想要做的事情在this SO post中有很好的描述。 ,但还没有一个公认的答案。
这是我到目前为止的代码:
import asyncio
from aiohttp import ClientSession
[.....]
async def call_endpoint_async(endpoint, data):
async with ClientSession() as session, session.post(url=endpoint, data=data) as result:
response = await result.read()
print(response)
return response
class CreateTestScores(APIView):
permission_classes = (IsAuthenticated,)
def post(self, request):
[.....]
asyncio.run(call_endpoint_async(url, data))
print('cp #1') # <== `async.io` BLOCKS -- PRINT STATEMENT DOESN'T RUN UNTIL `asyncio.run` RETURNS
在 Python 中执行 Ajax 风格的非阻塞 http 请求的正确方法是什么?
最佳答案
如果您的程序在 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')
但这要求“调用者”也是异步的。在您的情况下,您希望整个异步事件循环在后台运行,因此。这可以通过在单独的线程中运行它来实现,例如:
pool = concurrent.futures.ThreadPoolExecutor()
# ...
def post(self, request):
fut = pool.submit(asyncio.run, call_endpoint_async(url, data))
print('cp #1')
但是,在这种情况下,您将无法通过使用 asyncio 获得任何结果。由于您无论如何都在使用线程,因此您也可以首先调用同步函数,例如 requests.get()
。
关于python-3.x - Python 3.7 非阻塞请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58759274/