What is the purpose of mounting a Session object?
Asked Answered
M

1

21

I have seen something like this in a few code snippets and in the Requests documentation:

import requests
sess = requests.Session()
adapter = requests.adapters.HTTPAdapter(max_retries=20)
sess.mount('https://', adapter)

I am trying to get a better sense of what .mount() does here. In this case, is it only to increase the number of allowed retries for all calls to sess.request()? Is it emulating something like:

for _ in range(max_retries):
    try:
        return sess.request(...)
    except:
        pass

or is there more going on?

I know that requests.Session instances are initialized with adapters that have max_retries=0, so the above is just a hunch based on that.

It would just be helpful to know how specifically .mount() is altering the session object's behavior in this case.

Mccarthy answered 20/6, 2018 at 2:38 Comment(0)
W
14

.mount() really does what you think, it just mount a custom adapter to a given schema.

In your given example, it does just increase the number of allowed retries. But actually it can do more depending on what adapter is used.

For example, you can also change the connection pool size by HTTPAdapter(pool_maxsize=100). You can do some further customization by creating a total customized adapter such as MyHTTPAdapter.

The choice is given to you.

Wilfordwilfred answered 20/6, 2018 at 6:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.