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次提取。