Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How can i send multiple HTTP requests and receive the response?

How can I send like 1000 requests the fastest way? I know that you can send multiple request with grequests:

urls = [
    'sample.url/1',
    'sample.url/2',
    ...
]
request = (grequests.get(u) for u in urls)
print grequests.map(request)

But the return is not the content. What I need is to get the json data, so for example something like this:

request = (grequests.get(u) for u in urls)
content = grequests.json(request)
like image 564
cbl Avatar asked Sep 28 '15 18:09

cbl


People also ask

How do you send multiple HTTP requests in Python?

There are two basic ways to generate concurrent HTTP requests: via multiple threads or via async programming. In multi-threaded approach, each request is handled by a specific thread. In asynchronous programming, there is (usually) one thread and an event loop, which periodically checks for the completion of a task.

Can you send multiple HTTP requests at once?

- HTTP requests and responses can be pipelined on a connection. Pipelining allows a client to make multiple requests without waiting for each response, allowing a single TCP connection to be used much more efficiently, with much lower elapsed time.


1 Answers

The items returned are not the content, but they do include the content. You can fetch all of the content like so:

result = grequests.map(request)
content = '\n'.join(r.content for r in result) # raw content
text = '\n'.join(r.text for r in result)       # decoded content

You can parse the json like this:

result = grequests.map(request)
json = [r.json() for r in result]

Sample program:

import grequests
import pprint

urls = [
    'http://httpbin.org/user-agent',
    'http://httpbin.org/headers',
    'http://httpbin.org/ip',
]

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

json = [response.json() for response in responses]
pprint.pprint(json)

text = '\n'.join(response.text for response in responses)
print(text)
like image 124
Robᵩ Avatar answered Oct 06 '22 01:10

Robᵩ