限制 Python 每秒的 HTTP 请求数

Nav*_*een 7 python throttling bandwidth-throttling python-multithreading

我编写了一个从文件中获取 URL 并同时向所有 URL 发送 HTTP 请求的脚本。我现在想限制每秒请求HTTP的数量和每个接口(带宽eth0eth1在会话等)。有没有办法在 Python 上实现这一点?

Geo*_*rgi 3

您可以使用 Semaphore 对象,它是标准 Python 库的一部分: python doc

或者,如果您想直接使用线程,可以使用 wait([timeout])。

没有与 Python 捆绑在一起的可以在以太网或其他网络接口上工作的库。最低的可以是套接字。

根据您的回复,这是我的建议。注意 active_count。仅使用它来测试您的脚本是否只运行两个线程。在这种情况下,它们将是三个,因为第一个是您的脚本,然后您有两个 URL 请求。

import time
import requests
import threading

# Limit the number of threads.
pool = threading.BoundedSemaphore(2)

def worker(u):
    # Request passed URL.
    r = requests.get(u)
    print r.status_code
    # Release lock for other threads.
    pool.release()
    # Show the number of active threads.
    print threading.active_count()

def req():
    # Get URLs from a text file, remove white space.
    urls = [url.strip() for url in open('urllist.txt')]
    for u in urls:
        # Thread pool.
        # Blocks other threads (more than the set limit).
        pool.acquire(blocking=True)
        # Create a new thread.
        # Pass each URL (i.e. u parameter) to the worker function.
        t = threading.Thread(target=worker, args=(u, ))
        # Start the newly create thread.
        t.start()

req()
Run Code Online (Sandbox Code Playgroud)