简体   繁体   English

使用 requests.get() 和 requests.session().get() 的区别?

[英]Difference between using requests.get() and requests.session().get()?

Sometimes I see people invoke web API using requests.Session object:有时我看到人们使用 requests.Session 对象调用 Web API:

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

But sometimes they don't:但有时他们不会:

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

Can somebody explain when should we use Session and when we don't need them?有人能解释一下我们什么时候应该使用Session以及什么时候不需要它们吗?

Under the hood, requests.get() creates a new Session object for each request made.在幕后, requests.get()为每个请求创建一个新的Session对象。

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.例如,这允许您保留 cookie,并允许您重新使用用于所有连接的设置,例如标头和查询参数。 To top this all off, sessions let you take advantage of connection pooling;最重要的是,会话让您可以利用连接池; reusing connections to the same host.重用与同一主机的连接。

See the Sessions documentation :请参阅会话文档

The Session object allows you to persist certain parameters across requests. Session 对象允许您跨请求保留某些参数。 It also persists cookies across all requests made from the Session instance, and will use urllib3's connection pooling.它还在 Session 实例发出的所有请求中保留 cookie,并将使用 urllib3 的连接池。 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 ).因此,如果您向同一主机发出多个请求,底层 TCP 连接将被重用,这可能会导致性能显着提升(请参阅HTTP 持久连接)。

To quote the documentation引用文档

The Session object allows you to persist certain parameters across requests. Session 对象允许您跨请求保留某些参数。 It also persists cookies across all requests made from the Session instance.它还在从 Session 实例发出的所有请求中保留 cookie。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM