芹菜+Eventlet+非阻塞请求

2024-06-28 15:38:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我在芹菜中使用Pythonrequests来进行大量(~10/sec)API调用(包括GET、POST、PUT、DELETE)。每个请求大约需要5-10秒才能完成。

我尝试在eventlet池中运行芹菜工人,并发性为1000。

由于requests正在阻塞进程,因此每个并发连接都在等待一个请求。

如何使requests异步?


Tags: apigetput进程secdeletepostrequests
2条回答

docs

there are lots of projects out there that combine Requests with one of Python’s asynchronicity frameworks. Two excellent examples are grequests and requests-futures.

对于eventlet,您可以使用erequests

使用eventletmonkey patching使任何纯python库不阻塞。

  • 修补单个库

    # import requests  # instead do this:
    import eventlet
    requests = eventlet.import_patched('requests')
    

    可以将包erequestsgrequests拆分为这两行。

  • 修补所有内容

    import eventlet
    eventlet.monkey_patch()  # must execute as early as possible
    ...
    # everything is non-blocking now:
    import requests, amqp, memcache, paramiko, redis
    

更新:有带猴子修补请求库的known issue。如果你得到:

ImportError: cannot import name utils

,然后将导入行修改为

requests = eventlet.import_patched('requests.__init__')

相关问题 更多 >