2023-05-01 20:00:32 +09:00
|
|
|
from abc import ABC
|
|
|
|
|
|
|
|
import requests
|
|
|
|
from pydantic import parse_obj_as
|
|
|
|
from requests import Response
|
|
|
|
|
2023-05-09 13:08:50 +09:00
|
|
|
from mdrsclient.connection import MDRSConnection
|
2023-05-01 20:00:32 +09:00
|
|
|
from mdrsclient.exceptions import (
|
|
|
|
BadRequestException,
|
|
|
|
ForbiddenException,
|
|
|
|
UnauthorizedException,
|
|
|
|
UnexpectedException,
|
|
|
|
)
|
|
|
|
from mdrsclient.models import DRFStandardizedErrors
|
|
|
|
|
|
|
|
|
|
|
|
class BaseApi(ABC):
|
2023-05-09 13:08:50 +09:00
|
|
|
connection: MDRSConnection
|
|
|
|
|
|
|
|
def __init__(self, connection: MDRSConnection) -> None:
|
|
|
|
self.connection = connection
|
2023-05-01 20:00:32 +09:00
|
|
|
|
|
|
|
def _get(self, url, *args, **kwargs) -> Response:
|
2023-05-09 13:08:50 +09:00
|
|
|
return self.connection.session.get(self.__build_url(url), *args, **kwargs)
|
2023-05-01 20:00:32 +09:00
|
|
|
|
|
|
|
def _post(self, url, *args, **kwargs) -> Response:
|
2023-05-09 13:08:50 +09:00
|
|
|
return self.connection.session.post(self.__build_url(url), *args, **kwargs)
|
2023-05-01 20:00:32 +09:00
|
|
|
|
|
|
|
def _put(self, url, *args, **kwargs) -> Response:
|
2023-05-09 13:08:50 +09:00
|
|
|
return self.connection.session.put(self.__build_url(url), *args, **kwargs)
|
2023-05-01 20:00:32 +09:00
|
|
|
|
|
|
|
def _delete(self, url, *args, **kwargs) -> Response:
|
2023-05-09 13:08:50 +09:00
|
|
|
return self.connection.session.delete(self.__build_url(url), *args, **kwargs)
|
2023-05-01 20:00:32 +09:00
|
|
|
|
|
|
|
def _patch(self, url, *args, **kwargs) -> Response:
|
2023-05-09 13:08:50 +09:00
|
|
|
return self.connection.session.patch(self.__build_url(url), *args, **kwargs)
|
2023-05-01 20:00:32 +09:00
|
|
|
|
|
|
|
def _raise_response_error(self, response: Response) -> None:
|
|
|
|
if response.status_code >= 300:
|
|
|
|
if response.status_code < 400 or response.status_code >= 500:
|
|
|
|
raise UnexpectedException(f"Unexpected status code returned: {response.status_code}.")
|
|
|
|
errors = parse_obj_as(DRFStandardizedErrors, response.json())
|
|
|
|
if response.status_code == requests.codes.bad_request:
|
|
|
|
raise BadRequestException(errors.errors[0].detail)
|
|
|
|
elif response.status_code == requests.codes.unauthorized:
|
|
|
|
raise UnauthorizedException("Login required.")
|
|
|
|
elif response.status_code == requests.codes.forbidden:
|
|
|
|
raise ForbiddenException("You do not have enough permissions. Access is denied.")
|
|
|
|
else:
|
|
|
|
raise UnexpectedException(errors.errors[0].detail)
|
|
|
|
|
|
|
|
def __build_url(self, *args: tuple) -> str:
|
2023-05-09 13:08:50 +09:00
|
|
|
return self.connection.build_url(*args)
|