Python: how to reliably clean up httpx or requests session object in class?

Viewed 370

The recommended way to use httpx.Client() is as a context manager that will ensure the connections get properly cleaned-up upon exiting the with block.

But let us suppose I want to write a class that will instantiate an httpx.Client() session that can be reused throughout our code without having to put my entire script inside a with block.

class APIWrapper:
    def __init__(self):
        self.session = httpx.Client()
        self.token = fetch_oauth_token()

    def fetch_oauth_token(self, **kwargs):
        r = self.session.get(endpoint)
        # Perform an authorization_code flow.
        return token

    def get(self, endpoint):
        r = self.session.get(endpoint, headers=self.headers)
        return r

    def __exit__(self):
        self.session.close()

api = APIWrapper()
api.get('https://api.some.url/statistics?location=worldwide')
<1000 lines of code>
api.get('https://api.some.url/users?location=denver')

In the illustrative example above I'm hoping to use a session for the API's OAuth authentication flow and later it can be re-used for any API calls that the user makes.

  1. Is this a legit way to go about things or is it not a great idea? Would it be better to use separate sessions and force the user to use a with context manager for their own calls?

  2. While searching I have seen that a session needs to be closed under the class __exit__ function. Is using the __exit__ function sufficient for ensuring proper clean-up (even if exceptions were to occur)? Is it equivalent to using the with-block way of doing it?

0 Answers
Related