python-3.x - Python 3.7 非阻塞请求?

标签 python-3.x asynchronous request python-asyncio nonblocking

我想在 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/

相关文章:

Node.JS:如何在 URL 请求中使用百分号登录?

node.js - JSON.parse,JSON 中位置 0 处出现意外标记 T

python - 均值按两列分组,窗口为 3 个月,NaN 小于 3 个月

c# - 在Ui线程上执行同步操作

python - 在 Python 3 中,单字节 (\xd0) 被打印为两个字节的序列 (\xc3\x90)

c# - 使用 webclient DownloadFileAsync 多个文件

c# - 可测试异步操作的体面模式?

PHP 检查对其他服务器的请求是否正在运行

python - ValueError : Stop argument for islice() must be None or an integer: 0 <= x <= sys. maxsize 关于主题一致性

python - Tkinter - 在列表框选择时运行事件函数