Python 的 Requests 库线程中的 Session 对象是否安全? [英] Is the Session object from Python's Requests library thread safe?

查看:62
本文介绍了Python 的 Requests 库线程中的 Session 对象是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 流行的Requests 库在其主页上被认为是线程安全的,但没有提供更多细节.如果我调用 requests.session(),我可以像这样安全地将这个对象传递给多个线程:

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 pass this object to multiple threads like so:

session = requests.session()
for i in xrange(thread_count):
    threading.Thread(
        target=target,
        args=(session,),
        kwargs={}
    )

并在多个线程中使用相同的连接池发出请求?

and make requests using the same connection pool in multiple threads?

如果是这样,这是推荐的方法,还是应该为每个线程提供自己的连接池?(假设所有单个连接池的总大小之和等于一个大连接池的大小,如上面的那个.)每种方法的优缺点是什么?

If so, is this the recommended approach, or should each thread be given its own connection pool? (Assuming the total size of all the individual connection pools summed to the size of what would be one big connection pool, like the one above.) What are the pros and cons of each approach?

推荐答案

https://github.com/psf/requests/issues/1871 暗示 Session 不是线程安全的,并且至少有一位维护者建议每个线程使用一个 Session.

https://github.com/psf/requests/issues/1871 implies that Session is not thread-safe, and that at least one maintainer recommends one Session per thread.

我刚刚打开了https://github.com/psf/requests/issues/2766 澄清文档.

I just opened https://github.com/psf/requests/issues/2766 to clarify the documentation.

这篇关于Python 的 Requests 库线程中的 Session 对象是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆