GRequests: Asynchronous HTTP Requests with Gevent

0.7.0 · active · verified Wed Apr 15

grequests is a Python library that combines the popular `requests` library with `gevent` to enable easy asynchronous HTTP requests. It allows developers to send multiple HTTP requests concurrently, significantly reducing the time spent waiting for network I/O, particularly useful for tasks like web scraping and interacting with multiple API endpoints. The library's current version is 0.7.0, and while its release cadence is not strictly regular, it receives updates for compatibility and new features.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `grequests.map` and `grequests.imap_enumerated` to send multiple GET requests concurrently. It includes a custom exception handler and sets a timeout for individual requests. `grequests.map` returns a list of responses (or `None` for failed requests) in the order of the initial requests, while `grequests.imap_enumerated` yields (index, response) tuples as responses become available, not necessarily in the original request order.

import grequests
import time

urls = [
    'http://httpbin.org/delay/1',
    'http://httpbin.org/status/200',
    'http://httpbin.org/delay/3',
    'http://httpbin.org/status/500'
]

def exception_handler(request, exception):
    print(f"Request to {request.url} failed: {exception}")

start_time = time.time()

# Create a list of unsent Request objects
reqs = (
    grequests.get(u, timeout=2) for u in urls
)

# Send all requests concurrently using map
# Responses will be in the same order as requests, with None for failed ones
responses = grequests.map(reqs, exception_handler=exception_handler, size=5)

print(f"\n--- Responses (using map, took {time.time() - start_time:.2f}s) ---")
for response in responses:
    if response:
        print(f"URL: {response.url}, Status: {response.status_code}")
    else:
        print("Request failed or timed out.")

print("\n--- Responses (using imap_enumerated) ---")
# imap_enumerated yields (index, response) and includes Nones for failures
reqs_for_imap_enumerated = (
    grequests.get(u, timeout=2) for u in urls
)
for index, response in grequests.imap_enumerated(reqs_for_imap_enumerated, exception_handler=exception_handler, size=5):
    if response:
        print(f"Index: {index}, URL: {response.url}, Status: {response.status_code}")
    else:
        print(f"Index: {index}, Request failed or timed out.")

view raw JSON →