from justgetit.constants import * import httpx import toga class BackEnd(): """ This is the interface for the backend. Its a bit over the top to subclass it from a widget, but this way it has access to the app """ application = None def __init__(self, app): self.application = app async def post(self, endpoint, parameters, callback): """ Call the server, always with a POST, for a specific endpoint and the parameters in the body :param endpoint: the endpoint without /api/ (no slashes) :param parameters: A dict with the parameters for the call :param callback: def in the calling function to return to """ self.status = 0 self.payload = None if len(endpoint)>2: try: async with httpx.AsyncClient() as client: response = await client.post(f"{API}/{endpoint}", data=parameters) self.payload = response.json() self.status = int(self.payload['status']) except httpx.RequestError as exc: self.status = -2 # status 2 means we are in offline mode if self.status == -2: pass elif self.status == 0: await self.application.main_window.dialog( toga.InfoDialog("Oops", self.payload['message']) ) elif self.status == 2: await self.application.main_window.dialog( toga.InfoDialog("Thank you", self.payload['message']) ) callback(parameters, self.payload) def postwait(self, endpoint, parameters): """ Call the server, always with a POST, for a specific endpoint and the parameters in the body :param endpoint: the endpoint without /api/ (no slashes) :param parameters: A dict with the parameters for the call :param callback: def in the calling function to return to """ self.status = 0 self.payload = None if len(endpoint)>2: try: response = httpx.post(f"{API}/{endpoint}", data=parameters) self.payload = response.json() self.status = int(self.payload['status']) except httpx.RequestError as exc: self.status = -2 return self.payload