简体   繁体   English

为 requests.Session() 对象设置主机和端口

[英]Setting host and port for requests.Session() objects

How would I configure a Session() object so that all requests through it use the same host and port?我将如何配置Session() object 以便通过它的所有请求都使用相同的主机和端口?

Currently I would do the following:目前我会做以下事情:

urls = [f'https://somehost.com:1234/query?page={i}' for i in range(10)]
s = requests.Session()
for url in urls:
    r = s.get(url)

Is there not a way to explicitly set the host and port for persistent connections?有没有办法显式设置持久连接的主机和端口? For example:例如:

s = requests.Session()
s.host = 'https://somehost.com'
s.port = '1234'

From the requests documentation about sessions:从有关会话的requests文档中:

The Session object allows you to persist certain parameters across requests. Session object 允许您跨请求保留某些参数。 It also persists cookies across all requests made from the Session instance, and will use urllib3's connection pooling.它还在从 Session 实例发出的所有请求中保留 cookies,并将使用 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 持久连接)。

So while you give the url each time.所以当你每次给 url 时。 Under the hood requests will not be creating a new TCP socket connection for each request.引擎盖下的请求不会为每个请求创建新的 TCP 套接字连接。 It will reuse the TCP socket connection to this host and port from the connection pool.它将重用 TCP 套接字连接到此主机和连接池中的端口。

The main idea behind sessions is to share parameters and cookies between each request without having to set them individually in each request.会话背后的主要思想是在每个请求之间共享参数和 cookies,而不必在每个请求中单独设置它们。 and under the hood it will persist the connection.并且在引擎盖下它将保持连接。 but you still need to give the full URL in each call但您仍然需要在每次通话中提供完整的 URL

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

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