Python 频繁请求问题: [Errno 104] Connection reset by peer
2016-11-14 21:58
295 查看
Table of Contents
1. 记遇到的一个问题:[Errno 104] Connection reset by peer记遇到的一个问题:[Errno 104] Connection reset by peer
今天工作上有个需求,数据库有个表有将近3万条url记录,每条记录都是一个图片,我需要请求他们拿到每个图片存到本地。一开始我是这么写的(伪代码):import requests for url in urls: try: r = requests.get(url).content save_image(r) except Exception, e: print str(e)
然而在服务器上运行时, 会发现每隔一些请求会报类似下面的错误:
HTTPConnectionPool(host='wx.qlogo.cn', port=80): Max retries exceeded with url: /mmopen/aTVWntpJLCAr2pichIUx8XMevb3SEbktTuLkxJLHWVTwGfkprKZ7rkEYDrKRr5icyDGIvU4iasoyRrqsffbe3UUQXT5EfMEbYKg/0 (Caused by <class 'socket.error'>: [Errno 104] Connection reset by peer)
这让我想起了之前通过hacker news api 在自己电脑上请求一条一条数据时,为了加快处理速度,采用多进程的方式请求接口,也会出现这样的错误。之前我是做了错误记录直接pass了,这次情况下因为需要请求所有图片,在google查了相关原因,大概是因为我频繁请求,服务器关闭了部门请求连接。参见这里, 这里, 这里。
所以我粗暴地这么做,还真解决了:
import requests for url in urls: for i in range(10): try: r = requests.get(url).content except Exception, e: if i >= 9: do_some_log() else: time.sleep(0.5) else: time.sleep(0.1) break save_image(r)
代码很简陋,但可以说明大体解决方案,在每个请求间增加延时可以减少大部分请求拒绝,但还是存在一些请求被拒绝的,所以在那部分请求被拒绝后,发起重试,在被拒10次后才善罢甘休(记录到日志)。在实际的请求中,加了0.1s的延迟被拒绝的情况明显少了很多,被拒绝重试的次数最多为3次,最后成功地取下了全部图片。
相关文章推荐
- Python 频繁请求问题: [Errno 104] Connection reset by peer
- python httplib [Errno 104] Connection reset by peer问题
- python [Errno socket error] [Errno 104] Connection reset by peer
- python 爬虫 <class 'socket.error'>: [Errno 104] Connection reset by peer)
- urllib2.URLError: <urlopen error [Errno 104] Connection reset by peer>
- urllib2.URLError: <urlopen error [Errno 104] Connection reset by peer>
- urllib2.URLError: <urlopen error [Errno 104] Connection reset by peer>
- php502问题解决:recv() failed (104: Connection reset by peer) while reading response header from upstream
- ConnectionResetError: [Errno 104] Connection reset by peer
- ConnectionResetError: [Errno 104] Connection reset by peer
- pyspider连接rabbitmq ,结果出现socket.error: [Errno 104] Connection reset by peer 这样的报错信息
- urllib2.URLError: <urlopen error [Errno 104] Connection reset by peer>
- java.io.IOException: Connection reset by peer问题处理
- ab压测 apr_socket_recv: Connection reset by peer (104)错误解决方法
- OGG-01232 Receive TCP Params Error: TCP/IP Error 104 (Connection Reset By Peer).
- rsync错误处理-Connection reset by peer(104)
- 棘手问题java.net.SocketException: Connection reset by peer: socket write error未解决
- nginx 502 日志 . recv() failed (104: Connection reset by peer)报错
- Android通过Http协议POST请求异常(Connection reset by peer)
- 【OpenStack】SSH登录虚拟机出现"Read from socket failed: Connection reset by peer"问题的解决办法