Skip to content

Commit

Permalink
add support for a custom requests session in client
Browse files Browse the repository at this point in the history
  • Loading branch information
syphar committed Nov 28, 2023
1 parent b5ead78 commit 59773a4
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/personio_py/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,16 @@ class Personio:
PROJECT_URL = 'company/attendances/projects'

def __init__(self, base_url: str = None, client_id: str = None, client_secret: str = None,
dynamic_fields: List[DynamicMapping] = None):
dynamic_fields: List[DynamicMapping] = None,
session: Optional[requests.Session] = None):
self.base_url = base_url or self.BASE_URL
self.client_id = client_id or os.getenv('CLIENT_ID')
self.client_secret = client_secret or os.getenv('CLIENT_SECRET')
self.headers = {'accept': 'application/json'}
self.authenticated = False
self.dynamic_fields = dynamic_fields
self.search_index = SearchIndex(self)
self.session = session or requests.Session()

def authenticate(self):
"""
Expand All @@ -68,7 +70,7 @@ def authenticate(self):
url = urljoin(self.base_url, 'auth')
logger.debug(f"authenticating to {url} with client_id {self.client_id}")
params = {"client_id": self.client_id, "client_secret": self.client_secret}
response = requests.request("POST", url, headers=self.headers, params=params)
response = self.session.request("POST", url, headers=self.headers, params=params)
if response.ok:
token = response.json()['data']['token']
self.headers['Authorization'] = f"Bearer {token}"
Expand Down Expand Up @@ -107,7 +109,7 @@ def request(self, path: str, method='GET', params: Dict[str, Any] = None,
_headers.update(headers)
# make the request
url = urljoin(self.base_url, path)
response = requests.request(method, url, headers=_headers, params=params, json=data)
response = self.session.request(method, url, headers=_headers, params=params, json=data)
# re-new the authorization header
authorization = response.headers.get('Authorization')
if authorization:
Expand Down

0 comments on commit 59773a4

Please sign in to comment.