简体   繁体   中英

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?

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:

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).

So while you give the url each time. Under the hood requests will not be creating a new TCP socket connection for each request. It will reuse the TCP socket connection to this host and port from the connection pool.

The main idea behind sessions is to share parameters and cookies between each request without having to set them individually in each request. and under the hood it will persist the connection. but you still need to give the full URL in each call

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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