From a5eca9960e91cee441fd0302ad24a5c89c71a573 Mon Sep 17 00:00:00 2001 From: 3wc <3wc@doesthisthing.work> Date: Fri, 27 Oct 2023 21:11:29 +0100 Subject: [PATCH] Kimai API caching and nicer architecture --- hamstertools/kimai.py | 42 +++++++++++++++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/hamstertools/kimai.py b/hamstertools/kimai.py index 5d2f84c..0203f06 100644 --- a/hamstertools/kimai.py +++ b/hamstertools/kimai.py @@ -2,6 +2,11 @@ import requests import requests_cache import os + +class NotFound(Exception): + pass + + class KimaiAPI(object): # temporary hardcoded config KIMAI_API_URL = 'https://kimai.autonomic.zone/api' @@ -14,10 +19,16 @@ class KimaiAPI(object): 'X-AUTH-TOKEN': KIMAI_API_KEY } + def __init__(self): + requests_cache.install_cache('kimai', backend='sqlite', expire_after=1800) + self.customers_json = requests.get( + f'{self.KIMAI_API_URL}/customers?visible=3', headers=self.auth_headers).json() + self.projects_json = requests.get( + f'{self.KIMAI_API_URL}/projects?visible=3', headers=self.auth_headers).json() + class BaseAPI(object): def __init__(self, api, **kwargs): - requests_cache.install_cache('kimai', backend='sqlite', expire_after=1800) for key, value in kwargs.items(): setattr(self, key, value) @@ -28,12 +39,17 @@ class Customer(BaseAPI): @staticmethod def list(api): - response = requests.get( - f'{api.KIMAI_API_URL}/customers?visible=3', headers=api.auth_headers).json() return [ - Customer(api, c['id'], c['name']) for c in response + Customer(api, c['id'], c['name']) for c in api.customers_json ] + @staticmethod + def get_by_id(api, id): + for value in api.customers_json: + if value['id'] == id: + return Customer(api, value['id'], value['name']) + raise NotFound() + def __repr__(self): return f'Customer (id={self.id}, name={self.name})' @@ -44,16 +60,24 @@ class Project(BaseAPI): @staticmethod def list(api): - response = requests.get( - f'{api.KIMAI_API_URL}/projects?visible=3', headers=api.auth_headers).json() return [ - Project(api, p['id'], p['name'], p['customer']) for p in response + Project(api, p['id'], p['name'], Customer.get_by_id(api, p['customer'])) for p in api.projects_json ] + @staticmethod + def get_by_id(api, id): + for value in api.projects_json: + if value['id'] == id: + return Project(api, value['id'], value['name'], + Customer.get_by_id(api, value['customer'])) + raise NotFound() + def __repr__(self): return f'Project (id={self.id}, name={self.name}, customer={self.customer})' -customers = Customer.list(KimaiAPI()) -projects = Project.list(KimaiAPI()) +api = KimaiAPI() + +customers = Customer.list(api) +projects = Project.list(api) from pdb import set_trace; set_trace()