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.
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
withcontext manager for their own calls?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 thewith-block way of doing it?