使用 requests.get() 和 requests.session().get() 的区别?
Difference between using requests.get() and requests.session().get()?
有时我看到人们使用 requests.Session 对象调用网络 API:
client = requests.session()
resp = client.get(url='...')
但有时他们不会:
resp = requests.get(url='...')
有人可以解释一下我们什么时候应该使用 Session
什么时候不需要它们吗?
The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance.
在幕后,requests.get()
为每个发出的请求创建一个新的 Session
object。
通过预先创建 session object,您可以 重用 session;例如,这可以让您保留 cookie,并让您 re-use 设置用于所有连接,例如 headers 和查询参数。最重要的是,sessions 让您可以利用连接池;重用与同一主机的连接。
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.Session 对象调用网络 API:
client = requests.session()
resp = client.get(url='...')
但有时他们不会:
resp = requests.get(url='...')
有人可以解释一下我们什么时候应该使用 Session
什么时候不需要它们吗?
The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance.
在幕后,requests.get()
为每个发出的请求创建一个新的 Session
object。
通过预先创建 session object,您可以 重用 session;例如,这可以让您保留 cookie,并让您 re-use 设置用于所有连接,例如 headers 和查询参数。最重要的是,sessions 让您可以利用连接池;重用与同一主机的连接。
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).