Limiting number of HTTP requests per second on Python(在Python上限制每秒的HTTP请求数)
本文介绍了在Python上限制每秒的HTTP请求数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经编写了一个脚本,它从文件中获取URL并同时向所有URL发送HTTP请求。我现在想限制每秒的HTTP请求数和每个接口的带宽(eth0
、eth1
等)。)在一次治疗中。有什么办法可以在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请求数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:在Python上限制每秒的HTTP请求数


基础教程推荐
猜你喜欢
- 求两个直方图的卷积 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 包装空间模型 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01