Last active
August 16, 2019 11:52
-
-
Save afonasev/e5507a49af80b51c534f1016a6f89d68 to your computer and use it in GitHub Desktop.
requests.session with timeout and retries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Any | |
import requests | |
REQUEST_DEFAULT_TIMEOUT = 5 | |
REQUEST_RETRIES = 5 | |
class SessionWithTimeout(requests.Session): | |
def request(self, *args: Any, **kwargs: Any): | |
if kwargs['timeout'] is None: | |
kwargs['timeout'] = REQUEST_DEFAULT_TIMEOUT | |
return super().request(*args, **kwargs) | |
@classmethod | |
def with_retries(cls, max_retries=REQUEST_RETRIES) -> 'SessionWithTimeout': | |
# retry failed DNS lookups, socket connections and connection timeouts | |
http_session = cls() | |
retry_adapter = requests.adapters.HTTPAdapter(max_retries=max_retries) | |
http_session.mount('http://', retry_adapter) | |
http_session.mount('https://', retry_adapter) | |
return http_session | |
http_session = SessionWithTimeout.with_retries() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment