未使用Python requeststhreads调用延迟回调

2024-05-02 18:31:14 发布

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

我尝试使用Python中的请求库来执行异步HTTP请求。我发现这个库的最新版本不直接支持异步请求。为了实现这一点,他们提供了请求线程库,该库利用Twisted来处理异步性。我尝试修改提供的示例以使用回调而不是await/yield,但是没有调用回调。在

我的示例代码是:

session = AsyncSession(n=10)

def processResponse(response):
  print(response)

def main():
  a = session.get('https://reqres.in/api/users')
  a.addCallbacks(processResponse, processResponse)
  time.sleep(5)

请求线程库:https://github.com/requests/requests-threads


Tags: 代码https版本http利用示例responsesession
2条回答

我怀疑没有调用回调是因为您没有运行Twisted的eventloop(称为reactor)。删除你的睡眠功能并用reactor.run()替换它。在

from twisted.internet import reactor
# ...
def main():
    a = session.get('https://reqres.in/api/users')
    a.addCallbacks(processResponse, processResponse)
    #time.sleep(5)    # never use blocking functions like this w/ Twisted
    reactor.run()

catch is Twisted的reactor无法重新启动,因此一旦停止事件循环(即reactor.stop()),当再次执行reactor.run()时,将引发异常。换句话说,你的脚本/应用程序只会“运行一次”。为了避免这个问题,我建议您使用^{}。下面是一个使用requests-thread中类似示例的快速示例:

^{pr2}$

正如FYI requests-thread不适用于生产系统,且会发生重大变化(截至2017年10月)。本项目的最终目标是为requests设计一个可期待的设计模式。如果您需要支持生产的并发请求,请考虑grequests或{}。在

我想这里唯一的错误是你忘了运行reactor/event loop。在

以下代码适用于我:

from twisted.internet import reactor
from requests_threads import AsyncSession

session = AsyncSession(n=10)


def processResponse(response):
    print(response)


a = session.get('https://reqres.in/api/users')
a.addCallbacks(processResponse, processResponse)
reactor.run()

相关问题 更多 >