Kimai API caching and nicer architecture

This commit is contained in:
3wc 2023-10-27 21:11:29 +01:00
parent d88098dd30
commit a5eca9960e
1 changed files with 33 additions and 9 deletions

View File

@ -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()