As you know, sessions do not have timeout property and semantically it's applied to per-request mechanisms, not sessions.
I need to set timeout for session.get() method and though I tried some approaches I mention below, it doesn't work for me. Would you please tell me why and whether there is something I missed to notice? I use requests==2.25.0
How I create session:
def get_anonymous_session(self) -> requests.Session:
session = requests.Session()
session.cookies.update({'sessionid': '', 'mid': '', 'ig_pr': '1',
'ig_vw': '1920', 'csrftoken': '',
's_network': '', 'ds_user_id': ''})
session.headers.update(self._default_http_header(empty_session_only=True)
return session
Approach 1
class MyHTTPAdapter(requests.adapters.HTTPAdapter):
def __init__(self, timeout=None, *args, **kwargs):
self.timeout = timeout
super(MyHTTPAdapter, self).__init__(*args, **kwargs)
def send(self, *args, **kwargs):
kwargs['timeout'] = self.timeout
return super(MyHTTPAdapter, self).send(*args, **kwargs)
sess = self.get_anonymous_session()
sess.mount("https://[base-url]", MyHTTPAdapter(timeout=10))
Approach 2
sess = self.get_anonymous_session()
sess.request = partial(sess.request, timeout=10) # type: ignore
# or
sess.get = partial(sess.get, timeout=10)
question from:
https://stackoverflow.com/questions/65933047/python-requests-session-does-not-adhere-timeout-value 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…