我已经编写了一个脚本,用于从文件中获取URL并同时向所有URL发送HTTP请求。我现在想要限制会话中每秒HTTP请求的数量和每个接口的带宽(eth0
,eth1
等)。有没有什么办法可以在Python上实现这一点?在Python上每秒限制HTTP请求数
2
A
回答
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
你可以使用一个工人的概念,如文档中描述: https://docs.python.org/3.4/library/queue.html
添加您的工人中等待()命令来获取他们的请求之间的等待(从文档的例子:内“while true”在task_done之后)。
示例:5“Worker” - 请求之间的等待时间为1秒的线程将少于每秒5次提取。
相关问题
- 1. 这里API请求每秒限制
- 2. 如何限制HTTP请求到每2秒
- 3. Glassfish:限制用户每秒/每分钟的请求数量
- 4. 如何在apache基准工具中限制每秒请求数
- 5. 在制作http请求之前限制http请求
- 6. 如何使用Apache实现速率限制? (每秒请求数)
- 7. 运行“空”Undertow时,每秒HTTP请求的限制因素是什么?
- 8. 在Nginx中限制http请求
- 9. 在linux端口每秒请求计数
- 10. 服务器请求每秒
- 11. HTTP请求优化:什么是限制?
- 12. 使用Rxjs5(Beta)来限制http请求
- 13. 限制删除solr中的Http请求
- 14. 每秒测量出站请求数?
- 15. Amazon S3:每秒最大PUT请求数
- 16. 使用statsd测量每秒请求数
- 17. 如果在Apache2上每秒请求的请求太多,请阻止IP
- 18. HTTP请求(Python + VBA)
- 19. 限制请求仅请求HTTP/1.0 [防止块错误]
- 20. 检索Salesforce每日Api请求限制
- 21. 限制每个IP的TCP请求
- 22. 限制用户,使每秒
- 23. 如何限制每个用户每分钟的请求数?
- 24. 数据存储和30秒请求限制
- 25. 强制python http请求刷新
- 26. 如何限制每秒卷曲数php
- 27. ? HTTP请求每10秒和图表图像生成
- 28. NodeJS:如何每3秒同时发出多个HTTP请求?
- 29. Express.js - 对每个HTTP请求
- 30. 每秒发送更多than1000请求在python
我如何将它附加到我的脚本中?我是一名Python初学者。 – Naveen 2014-09-29 11:44:32
您需要发布您的源代码(线程部分)以便让某人有所帮助。正如Python所言:“信号量经常被用来保护有限容量的资源”。从以下开始,稍后展开以适合您的代码。首先设置一个限制= 5,然后你需要一个线程池 - > pool = BoundedSemaphore(value = limit)。然后通过pool.acquire()锁定一个线程,发送http请求(例如urllib2),最后通过pool.release()解锁线程。 – Georgi 2014-10-01 08:45:19
进口穿线 导入时间 导入请求 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