如何从 Flask 服务器异步发送多个请求



所以我正在构建一个 Flask API,我有一个 GET 路由,它基本上将 5 个请求发送到另一个 API 以收集我然后合并并返回的数据。

这样:

results = [requests.get('http://localhost:9000/ss/1'),
            requests.get('http://localhost:9000/ss/2'),
        requests.get('http://localhost:9000/ss/3'),
       requests.get('http://localhost:9000/ss/4'),
            requests.get('http://localhost:9000/ss/5')]

问题是每个请求大约需要 2 秒,因此需要 10 秒才能关闭。如何使用不同的线程使所有请求异步,因此总共需要大约 2 秒?然后,如何告诉 API 在它们全部加载后开始合并它们?

任何帮助将不胜感激!

您可以使用grequests最初基于我认为和请求的gevent的package( https://pypi.python.org/pypi/grequests(。

代码非常简单:

urls = [url1,url2,...]
#prepare the shells 
shells = (grequests.get(u) for u in urls)
#start all requests at the same time
responses = grequests.map(shells) #will output a list of responses that you can access

最新更新