Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow for custom requests sessions #22

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions cortex4py/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ def __init__(self, url, api_key, **kwargs):
self.__base_url = '{}/api/'.format(url)
self.__proxies = kwargs.get('proxies', {})
self.__verify_cert = kwargs.get('verify_cert', kwargs.get('cert', True))
self.__session = kwargs.get('session', None)

self.organizations = OrganizationsController(self)
self.users = UsersController(self)
Expand All @@ -55,13 +56,22 @@ def __recover(exception):
else:
raise CortexError("Unexpected exception") from exception

@property
def session(self):
# if no custom session object has been provided by the user
if self.__session is None:
# start a fresh session without cookies for each request
return requests.sessions.Session()

return self.__session

def do_get(self, endpoint, params={}):
headers = {
'Authorization': 'Bearer {}'.format(self.__api_key)
}

try:
response = requests.get('{}{}'.format(self.__base_url, endpoint),
response = self.session.get('{}{}'.format(self.__base_url, endpoint),
headers=headers,
params=params,
proxies=self.__proxies,
Expand All @@ -78,7 +88,7 @@ def do_file_post(self, endpoint, data, **kwargs):
}

try:
response = requests.post('{}{}'.format(self.__base_url, endpoint),
response = self.session.post('{}{}'.format(self.__base_url, endpoint),
headers=headers,
proxies=self.__proxies,
data=data,
Expand All @@ -96,7 +106,7 @@ def do_post(self, endpoint, data, params={}, **kwargs):
}

try:
response = requests.post('{}{}'.format(self.__base_url, endpoint),
response = self.session.post('{}{}'.format(self.__base_url, endpoint),
headers=headers,
proxies=self.__proxies,
json=data,
Expand All @@ -115,7 +125,7 @@ def do_patch(self, endpoint, data, params={}):
}

try:
response = requests.patch('{}{}'.format(self.__base_url, endpoint),
response = self.session.patch('{}{}'.format(self.__base_url, endpoint),
headers=headers,
proxies=self.__proxies,
json=data,
Expand All @@ -132,7 +142,7 @@ def do_delete(self, endpoint):
}

try:
response = requests.delete('{}{}'.format(self.__base_url, endpoint),
response = self.session.delete('{}{}'.format(self.__base_url, endpoint),
headers=headers,
proxies=self.__proxies,
verify=self.__verify_cert)
Expand Down