我的要求是生成hundreds of HTTP POST requests per second
。我正在使用它urllib2
.
def send():
req = urllib2.Request(url)
req.add_data(data)
response = urllib2.urlopen(req)
while datetime.datetime.now() <= ftime:
p=Process(target=send, args=[])
p.start()
time.sleep(0.001)
问题是这段代码sometimes for some iterations
抛出以下异常之一:
HTTP 503 Service Unavailable.
URLError: <urlopen error [Errno -2] Name or service not known>
我尝试过使用requests(HTTP for humans)
以及,但我对该模块有一些代理问题。似乎requests
即使目标计算机位于同一 LAN 内,也会向代理服务器发送 http 数据包。我不希望数据包发送到代理服务器。
限制并发连接数的最简单方法是使用线程池:
#!/usr/bin/env python
from itertools import izip, repeat
from multiprocessing.dummy import Pool # use threads for I/O bound tasks
from urllib2 import urlopen
def fetch(url_data):
try:
return url_data[0], urlopen(*url_data).read(), None
except EnvironmentError as e:
return url_data[0], None, str(e)
if __name__=="__main__":
pool = Pool(20) # use 20 concurrent connections
params = izip(urls, repeat(data)) # use the same data for all urls
for url, content, error in pool.imap_unorderred(fetch, params):
if error is None:
print("done: %s: %d" % (url, len(content)))
else:
print("error: %s: %s" % (url, error))
503 Service Unavailable
是服务器错误。它可能无法处理负载。
Name or service not known
是一个dns错误。如果您需要提出很多要求;安装/启用本地缓存 dns 服务器。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)