Is the Session object from Python's Requests library thread safe?

后端 未结 2 686
旧巷少年郎
旧巷少年郎 2020-12-05 16:59

Python\'s popular Requests library is said to be thread-safe on its home page, but no further details are given. If I call requests.session(), can I then safely

2条回答
  •  一生所求
    2020-12-05 17:35

    After reviewing the source of requests.session, I'm going to say the session object might be thread-safe, depending on the implementation of CookieJar being used.

    Session.prepare_request reads from self.cookies, and Session.send calls extract_cookies_to_jar(self.cookies, ...), and that calls jar.extract_cookies(...) (jar being self.cookies in this case).

    The source for Python 2.7's cookielib acquires a lock (threading.RLock) while it updates the jar, so it appears to be thread-safe. On the other hand, the documentation for cookielib says nothing about thread-safety, so maybe this feature should not be depended on?

    UPDATE

    If your threads are mutating any attributes of the session object such as headers, proxies, stream, etc. or calling the mount method or using the session with the with statement, etc. then it is not thread-safe.

提交回复
热议问题