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

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

问题描述

Python流行的请求库在其主页上被认为是线程安全的,但未提供更多详细信息。如果我调用 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/kennethreitz/requests/issues / 1871 表示Session不是线程安全的,并且至少一个维护者建议每个线程一个Session。

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

我刚刚打开https://github.com/kennethreitz/requests/issues/2766 来澄清文档。

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

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

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