I am using the python requests
library to intereact with an api.
I am first authenticating, getting a session-id
and then creating a request session
to persist that connection.
So I created a class to do this, but every time I use the class I am reinitialising and doing the authentication again. Which I want to avoid. Essentially I created an API between the API I am calling using DRF. How can I ensure that only 1 authenticated session is used across the entire app and that it persists through multiple request?
The class:
class RestClient:
session = None
def create_rest_client(self):
auth = requests.auth.HTTPBasicAuth(
USERNAME,
PASSWORD
)
response = requests.post(
f'https://{ settings.HOST }/rest/session',
auth=auth
)
session = requests.Session()
session_id = response.json().get('value')
session.headers.update({'api-session-id': session_id})
return session
def get_rest_client(self):
if self.session:
return self.session
else:
return self.create_rest_client()
Using the class I instantiate and get the client (naturally redoing the auth). I think this should either be global or a singleton.
Using class:
class ProductDetail(APIView):
def get(self, request, format=None, **kwargs):
response = []
rest_client = RestClient()
session = rest_client.get_rest_client()
response = session.get(
....use authenticated session
)
return Response(response.json())
session
on an instance of aRestClient
object and just pass that instance around where needed?requests.Session
and override the__init__
accordingly to make the initial request to update its own headers... then just pass that object around and treat it as though it was any otherrequests.Session
object...pass the object around
bit. Could you give an example?