在Python上限制每秒的HTTP请求数 [英] Limiting number of HTTP requests per second on Python

查看:9
本文介绍了在Python上限制每秒的HTTP请求数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个脚本,它从文件中获取URL并同时向所有URL发送HTTP请求。我现在想限制每秒的HTTP请求数和每个接口的带宽(eth0eth1等)。)在一次治疗中。有什么办法可以在Python上实现这一点吗?

推荐答案

您可以使用信号量对象,它是标准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()

这篇关于在Python上限制每秒的HTTP请求数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆