Skip to content

Commit

Permalink
Minor changes.
Browse files Browse the repository at this point in the history
  • Loading branch information
1 parent b109a0f commit af97e61
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 15 deletions.
50 changes: 45 additions & 5 deletions src/HaloPSA/Halo.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import urllib.parse
import json
import os
from functions import apiCaller
from src.HaloPSA.functions import apiCaller


# CONSTANTS
Expand Down Expand Up @@ -76,6 +76,7 @@ def __init__(self):
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
}
self.formattedParams = []


def get(self,
Expand Down Expand Up @@ -172,6 +173,7 @@ def update(self,
site_id:int=None,
users:list=None,
fields:list=None,
queueMode:str='disabled',
**others
):
"""Creates or updates one or more assets. If ID is included, asset(s) will be updated. If ID is not included new asset(s) will be created.
Expand All @@ -181,16 +183,32 @@ def update(self,
client_id (int, optional): Client ID.
site_id (int, optional): Site ID.
users (list, optional): User IDs.
fields (list, optional): Fields to be updated.
fields (list, optional): Fields to be updated.
queueMode (str, optional): Queue asset data to be sent as a batch update. Valid modes: disabled - Default, will update asset immediately. queue
Returns:
_type_: I dont think it returns anything...
"""
if queueMode.lower() not in ['disabled','queue','update']:
raise AttributeError(f'{queueMode} is not a valid Queue Mode.')

newVars = locals().copy()
request = apiCaller(HALO_API_URL,'update','Asset',newVars,self.headerJSON)
response = request.getData()
return response

if queueMode == 'disabled': # Sent request immediately
request = apiCaller(HALO_API_URL,'update','Asset',newVars,self.headerJSON)
response = request.getData()
return response

elif queueMode == 'queue': # Queue request.
self.formattedParams += [_formatter(newVars)]

elif queueMode == 'update':
request = apiCaller(HALO_API_URL,'update','Asset',newVars,self.headerJSON, self.formattedParams)
response = request.getData()
self.formattedParams = [] # reset queue
return response




class clients:
Expand Down Expand Up @@ -645,6 +663,28 @@ def manualTokenUpdate(key,id):
return attemptUpdate


def _formatter(params):
formattedData = {}
paramsToAdd = params | params['others'] # Copy params and add any additional items

# Remove Remove unneeded variables
paramsToAdd.pop('others')
paramsToAdd.pop('self')
paramsToAdd.pop('queueMode')

pageinateToggle = False
for item, value in paramsToAdd.items(): # Check params, add anything that isn't blank to the query

if item == 'pageinate' and value == True:
pageinateToggle = True

if pageinateToggle == False and item in ['page_size','page_no']: # Skip redundant values
continue

if value !=None:
formattedData.update({item : value})
return formattedData


### OLD SHIT ###

Expand Down
23 changes: 13 additions & 10 deletions src/HaloPSA/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
class apiCaller:
"""All available functions, endpoint independant"""

def __init__(self, baseURL, function, endpoint, params, header,*payload):
def __init__(self, baseURL, function, endpoint, params, header, payload=None):
self.allEndpoints = ['Action','Agent','Appointment','Asset','Attachment','Client','ClientContract','Invoice','Item','KBArticle','Opportunities','Projects','Quotation','Report','Site','Status','Supplier','Team','TicketType','Tickets','Users','RecurringInvoice','RecurringInvoice/UpdateLines'] # Endpoints function can be used with

if function.lower() not in ['search','get','update','delete','me']:
if function.lower() not in ['search','get','update','delete','me','queue']:
raise Exception('Invalid function')
elif endpoint not in self.allEndpoints:
raise Exception('Invalid endpoint')
Expand All @@ -21,11 +21,10 @@ def __init__(self, baseURL, function, endpoint, params, header,*payload):
self.validParams = [] # Placeholder for validation later
self.header = header
self.params = params
self.payload = '' if len(payload) == 0 else payload
self.payload = None if payload == None else payload

self._formatter() # Format data


if function.lower() == 'search':
query = urllib.parse.urlencode(self.formattedData)
self.url += '?' + query
Expand All @@ -39,14 +38,17 @@ def __init__(self, baseURL, function, endpoint, params, header,*payload):
self._requester('get')

elif function.lower() == 'update':
self.payload = json.dumps([self.formattedData],indent=4)
if payload == None:
self.payload = json.dumps([self.formattedData],indent=4)
else:
self.payload = json.dumps(self.payload)
pass
self._requester('post')

elif function.lower() == 'delete':
self.delete()



def getData(self):
return self.responseData

Expand Down Expand Up @@ -80,7 +82,7 @@ def _requester(self,method):

# Success
if code in [200,201]:
# 201 = Created
# 201 = Created/updated
# 200 = OK
self.responseData = content

Expand All @@ -91,9 +93,8 @@ def _requester(self,method):
print('The specified \'client_secret\' is invalid')
else:
print(content["error_description"])
elif code in [400]:
print(f'{code} - Bad Request')
raise Exception( f'{code} - Bad Request')
elif code in [400]: # Bad reqeust
raise Exception(f'{code} Bad Request - {content('ClassName')}: {content('message')}') # URL is good, but the request is no

# Add unique failures as found

Expand Down Expand Up @@ -127,3 +128,5 @@ def testFunc(test='word',b=2,**other):
if __name__=="__main__":
testFunc(data=2,otherData=3)



0 comments on commit af97e61

Please sign in to comment.