1
0
mirror of https://github.com/eternnoir/pyTelegramBotAPI.git synced 2023-08-10 21:12:57 +03:00

RETRY_ENGINE

Added RETRY_ENGINE var to api_helper.

Added RETRY_ENGINE = 2 based on native "requests" retry mechanism.
This commit is contained in:
Badiboy 2021-11-07 23:02:23 +03:00
parent 4a274ba440
commit 5ac71baafe

View File

@ -9,6 +9,7 @@ except ImportError:
import requests
from requests.exceptions import HTTPError, ConnectionError, Timeout
from requests.adapters import HTTPAdapter
try:
# noinspection PyUnresolvedReferences
@ -38,6 +39,7 @@ SESSION_TIME_TO_LIVE = 600 # In seconds. None - live forever, 0 - one-time
RETRY_ON_ERROR = False
RETRY_TIMEOUT = 2
MAX_RETRIES = 15
RETRY_ENGINE = 1
CUSTOM_SERIALIZER = None
CUSTOM_REQUEST_SENDER = None
@ -107,45 +109,48 @@ def _make_request(token, method_name, method='get', params=None, files=None):
params = params or None # Set params to None if empty
result = None
if RETRY_ON_ERROR:
if RETRY_ON_ERROR and RETRY_ENGINE == 1:
got_result = False
current_try = 0
while not got_result and current_try<MAX_RETRIES-1:
current_try+=1
try:
result = _get_req_session().request(
method, request_url, params=params, files=files,
timeout=(connect_timeout, read_timeout), proxies=proxy)
got_result = True
except HTTPError:
logger.debug("HTTP Error on {0} method (Try #{1})".format(method_name, current_try))
time.sleep(RETRY_TIMEOUT)
except ConnectionError:
logger.debug("Connection Error on {0} method (Try #{1})".format(method_name, current_try))
time.sleep(RETRY_TIMEOUT)
except Timeout:
logger.debug("Timeout Error on {0} method (Try #{1})".format(method_name, current_try))
time.sleep(RETRY_TIMEOUT)
if not got_result:
result = _get_req_session().request(
method, request_url, params=params, files=files,
timeout=(connect_timeout, read_timeout), proxies=proxy)
elif RETRY_ON_ERROR and RETRY_ENGINE == 2:
http = _get_req_session()
retry_strategy = requests.packages.urllib3.util.retry.Retry(
total=MAX_RETRIES,
)
adapter = HTTPAdapter(max_retries=retry_strategy)
for prefix in ('http://', 'https://'):
http.mount(prefix, adapter)
result = http.request(
method, request_url, params=params, files=files,
timeout=(connect_timeout, read_timeout), proxies=proxy)
elif CUSTOM_REQUEST_SENDER:
result = CUSTOM_REQUEST_SENDER(
method, request_url, params=params, files=files,
timeout=(connect_timeout, read_timeout), proxies=proxy)
else:
if CUSTOM_REQUEST_SENDER:
result = CUSTOM_REQUEST_SENDER(
method, request_url, params=params, files=files,
timeout=(connect_timeout, read_timeout), proxies=proxy)
else:
result = _get_req_session().request(
method, request_url, params=params, files=files,
timeout=(connect_timeout, read_timeout), proxies=proxy)
result = _get_req_session().request(
method, request_url, params=params, files=files,
timeout=(connect_timeout, read_timeout), proxies=proxy)
logger.debug("The server returned: '{0}'".format(result.text.encode('utf8')))