2

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

回答

0

你可以使用信号灯对象,它是标准的Python lib中的一部分: python doc

或者,如果您想直接与线程工作,你可以使用等待([超时])。

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

根据您的回复,这里是我的建议。注意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() 
+0

我如何将它附加到我的脚本中?我是一名Python初学者。 – Naveen 2014-09-29 11:44:32

+0

您需要发布您的源代码(线程部分)以便让某人有所帮助。正如Python所言:“信号量经常被用来保护有限容量的资源”。从以下开始,稍后展开以适合您的代码。首先设置一个限制= 5,然后你需要一个线程池 - > pool = BoundedSemaphore(value = limit)。然后通过pool.acquire()锁定一个线程,发送http请求(例如urllib2),最后通过pool.release()解锁线程。 – Georgi 2014-10-01 08:45:19

+0

进口穿线 导入时间 导入请求 DEF REQ(): 网址= [url.strip(),用于打开URL( 'urllist.txt中')] 用于Ü在范围(LEN(网址)): ř = requests.get(网址[U]) 打印r.status_code,网址[U] 线程= [] 线程= threading.Thread(目标= REQ) threads.start() – Naveen 2014-10-01 09:27:11

0

你可以使用一个工人的概念,如文档中描述: https://docs.python.org/3.4/library/queue.html

添加您的工人中等待()命令来获取他们的请求之间的等待(从文档的例子:内“while true”在task_done之后)。

示例:5“Worker” - 请求之间的等待时间为1秒的线程将少于每秒5次提取。