简体   繁体   English

Python:基于初始请求并发运行多个http请求?

[英]Python: Running multiple http requests concurrently based on an initial request?

Currently I am trying to fetch from an API which has 2 endpoints: 目前,我正在尝试从具有2个端点的API中获取:

GET /AllUsers 
GET /user_detail/{id}

In order to get the details of all the users, I would have to call GET /AllUsers , and loop through the IDs to call the GET /user_detail/{id} endpoint 1 by 1. I wonder if it's possible to have multiple GET /user_detail/{id} calls running at the same time? 为了获取所有用户的详细信息,我必须调用GET /AllUsers ,并遍历ID以1调用GET /user_detail/{id}端点1。我想知道是否可以使用多个GET /user_detail/{id}呼叫是否同时运行? Or perhaps there is a better approach? 还是有更好的方法?

This sounds like a great use case for grequests 这听起来像是grequest的好用例

import grequests

urls = [f'http://example.com/user_detail/{id}' for id in range(10)]

rs = (grequests.get(u) for u in urls)
responses = grequests.map(rs)

Edit : As an example for processing responses to retrieve json you could: 编辑 :作为处理响应以检索json的示例,您可以:

data = []
for response in responses:
    data.append(response.json())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM