使用 requests.get() 和 requests.session().get() 的区别? [英] Difference between using requests.get() and requests.session().get()?

查看:70
本文介绍了使用 requests.get() 和 requests.session().get() 的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我看到人们使用 requests.Session 对象调用 Web API:

Sometimes I see people invoke web API using requests.Session object:

client = requests.session()
resp = client.get(url='...')

但有时他们不会:

resp = requests.get(url='...')

谁能解释一下我们什么时候应该使用Session,什么时候不需要它们?

Can somebody explain when should we use Session and when we don't need them?

推荐答案

在幕后,requests.get() 为每个发出的请求创建一个新的 Session 对象.

Under the hood, requests.get() creates a new Session object for each request made.

通过预先创建会话对象,您可以重用会话;例如,这允许您保留 cookie,并允许您重新使用用于所有连接的设置,例如标头和查询参数.最重要的是,会话让您可以利用连接池;重用与同一主机的连接.

By creating a session object up front, you get to reuse the session; this lets you persist cookies, for example, and lets you re-use settings to be used for all connections such as headers and query parameters. To top this all off, sessions let you take advantage of connection pooling; reusing connections to the same host.

请参阅Sessions 文档一个>:

See the Sessions documentation:

Session 对象允许您跨请求保留某些参数.它还在 Session 实例发出的所有请求中保留 cookie,并将使用 urllib3 的连接池.因此,如果您向同一主机发出多个请求,底层 TCP 连接将被重用,这可能会显着提高性能(请参阅 HTTP 持久连接).

The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance, and will use urllib3‘s connection pooling. So if you’re making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase (see HTTP persistent connection).

这篇关于使用 requests.get() 和 requests.session().get() 的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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