electronics-inventory/electronics_inventory/spaceventory.py

154 lines
4.0 KiB
Python

#!/usr/bin/python3
import requests
import json
import enum
import os
from typing import List, Dict, Union, Optional
from dataclasses import dataclass
from uuid import UUID
@dataclass
class Item:
class State(enum.Enum):
PRESENT = "present"
MISSING = "missing"
TAKEN = "taken"
description: str
parent: str
uuid: str
labels: List[str]
state: State
props: Dict[str, str]
def __init__(
self,
name,
description=None,
parent=None,
uuid=None,
state=State.PRESENT,
labels=None,
props={},
):
self.name = str(name)
self.description = None
self.parent = None
self.uuid = None
self.labels = None
if description is not None:
self.description = str(description)
if parent is not None:
self.parent = str(parent)
if uuid is not None:
self.uuid = str(uuid)
if labels is not None:
self.labels = [str(label) for label in labels]
self.state = self.State(state)
self.props = dict(props)
# def __repr__(self):
# return f"<{self.__class__.__name__!s}(id='{self.uuid[:8]!s}', name='{self.name}')>"
@classmethod
def from_dict(cls, _dict: Dict[str, str]):
name = _dict["name"]
description = _dict["description"]
parent = _dict["parent"]
_uuid = _dict["uuid"]
state = _dict.get("state", cls.State.PRESENT)
props = _dict.get("props", dict())
labels = _dict.get("labels", [])
return cls(
name=name,
description=description,
parent=parent,
uuid=_uuid,
state=state,
labels=labels,
props=props,
)
API_URL = "https://inventory.waw.hackerspace.pl/api/1/"
class Inventory:
def __init__(self, token: Optional[str] = None, api_url: str = API_URL):
self.token = token
self.headers = {
"content-type": "application/json",
}
if token is not None:
self.headers["Authorization"] = f"Token {token}"
self.api_url = api_url
def _check_response(self, r):
if not r.ok:
raise Exception(str(r.text))
def get(self, path):
ret = requests.get(
self.api_url + str(path) + "?format=json", headers=self.headers
)
self._check_response(ret)
return ret.json()
def post(self, path, data):
ret = requests.post(
self.api_url + str(path), data=json.dumps(data), headers=self.headers
)
self._check_response(ret)
return ret.json()
def put(self, path, data):
ret = requests.put(
self.api_url + str(path), data=json.dumps(data), headers=self.headers
)
self._check_response(ret)
return ret.json()
def patch(self, path, data):
ret = requests.patch(
self.api_url + str(path), data=json.dumps(data), headers=self.headers
)
self._check_response(ret)
return ret.json()
def delete(self, path):
ret = requests.delete(self.api_url + str(path), headers=self.headers)
self._check_response(ret)
def delete_item(self, uuid):
ret = self.delete("items/{:s}".format(uuid))
self._check_response(ret)
def _get_uuid(self, i):
if isinstance(i, Item):
_uuid = i.uuid
elif isinstance(i, str):
_uuid = str(i)
else:
raise ValueError()
UUID(_uuid)
return _uuid
def get_item(self, item: Union[str, Item]):
_uuid = self._get_uuid(item)
r = self.get("items/{:s}".format(_uuid))
return Item.from_dict(r)
def get_children(self, parent: Union[str, Item]):
"""return list of children of item"""
_uuid = self._get_uuid(parent)
r = self.get("items/{:s}/children".format(_uuid))
cs = []
for c in r:
cs.append(Item.from_dict(c))
return cs