失败时如何重试urllib2.request? [英] How to retry urllib2.request when fails?

查看:276
本文介绍了失败时如何重试urllib2.request?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

urllib2.request 达到超时时,会引发 urllib2.URLError 异常。
重试建立连接的pythonic方法是什么?

When urllib2.request reaches timeout, a urllib2.URLError exception is raised. What is the pythonic way to retry establishing a connection?

推荐答案

我会使用 retry 装饰器。还有其他一些,但是这个很好用。使用方法如下:

I would use a retry decorator. There are other ones out there, but this one works pretty well. Here's how you can use it:

@retry(urllib2.URLError, tries=4, delay=3, backoff=2)
def urlopen_with_retry():
    return urllib2.urlopen("http://example.com")

如果引发 URLError ,它将重试该函数。检查上面的链接以获取有关参数的文档,但基本上,它最多可重试4次,每次的指数退避延迟都加倍,例如3秒,6秒,12秒。

This will retry the function if URLError is raised. Check the link above for documentation on the parameters, but basically it will retry a maximum of 4 times, with an exponential backoff delay doubling each time, e.g. 3 seconds, 6 seconds, 12 seconds.

这篇关于失败时如何重试urllib2.request?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆