Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

python requests.Session() does not adhere timeout value

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...