文章目录

普通做法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# 第一种方式 def retry (attempt): def decorator(func): def wrapper (*args, **kw) : att = 0 while att < attempt: try: return func (*args,**kw) except Exception as e: print(e) att += 1 return wrapper return decorator @retry(attempt=2) def get_response(url): r = requests.get(url) return r if __name__ == '__main__': r = get_response("http://www.baidu.com") print(r.status_code) |
retry 模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# coding:utf-8 from requests.exceptions import ConnectTimeout import requests from retry import __author__ = 'songhao' # 第二中方法 @retry(exceptions=ConnectTimeout, tries=3) def do_other(ourl): print(ourl, 'ddddddddddd') r = requests.get(ourl, timeout=1) return r.text if __name__ == '__main__': ourl = "https://www.google.com" do_some(ourl) try: do_other(ourl) except Exception as e: print("dssssssssss") pass |
retrying 模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import requests from retrying import retry @retry(stop_max_attempt_number=2) def get_html(url): print(url) r = requests.get(url,timeout=2) return r.status_code if __name__ == "__main__": try: a = get_html("https://www.baidu.com") except Exception as e: print(e,'------------') if 'a' in locals().keys(): print(a) else: a = 0 print(a) |
Requests 失败重试
1 2 3 4 5 6 7 8 9 10 11 12 |
from requests.packages.urllib3.util import Retry from requests.adapters import HTTPAdapter from requests import Session, exceptions s = Session() s.mount('https://', HTTPAdapter( max_retries=Retry(total=5, status_forcelist=[500]) ) ) s.get('https://httpbin.org/status/500') |
