When doing interface automation test, we always encounter interface script failure due to connection timeout and other errors.
Official method:
max_retries=5 error retries 5 times
Note that this is only for DNS, connection error retry.
from requests.adapters import HTTPAdapter s = requests.Session() s.mount('http://',HTTPAdapter(max_retries=5)) s.mount('https://',HTTPAdapter(max_retries=5)) s.get('https://www.baidu.com')
Self made decorator I
from requests.exceptions import ConnectionError import requests def retry(**kw): def war(func): def w(*args,**kwargs): try: ret = func(*args,**kwargs) except ConnectionError: kw['reNum'] = int(kw['reNum']) - 1 if kw['reNum'] >=0: print kw['reNum'] ret = w(*args,**kwargs) else: ret = ConnectionError return ret return w return war
Self made decorator II
from requests.exceptions import ConnectionError def retry(**kw): def wrapper(func): def _wrapper(*args,**kwargs): raise_ex = None for _ in range(kw['reNum']): print _ try: return func(*args,**kwargs) except ConnectionError as ex: raise_ex = ex #raise raise_ex return _wrapper return wrapper
Use method: reNum = 5 represents that the connection error can be retried up to 5 times.
@retry(reNum=5) def demo(): raise ConnectionError
Summary:
1. It's not that hard to write decorators, as long as you master the methods. This can be referred to in my previous article on decorators
2. The general explanation of decorators is to do something before and after the function. We can do a lot with this.
3. About request connection error, Retry, decorator; the principle is to make a loop, as long as there is a ConnectionError error caught, enter the next loop
Call; returns the function as long as it is correct.
qq technology exchange group, looking forward to your joining:
python test technology exchange group: 563227894
python test technology exchange group: 563227894
python test technology exchange group: 563227894