add base request/response classes

This commit is contained in:
Hay1tsme 2023-02-25 18:50:35 -05:00
parent b31e739ecd
commit b07e3d6a94

View File

@ -0,0 +1,38 @@
from urllib import parse
class DivaRequestParseException(Exception):
"""
Exception raised when there is a fault in parsing a diva request,
either due to a malformed request, or missing required items
"""
def __init__(self, message: str) -> None:
self.message = message
super().__init__(self.message)
class BaseRequest:
def __init__(self, raw: str) -> None:
self.raw = dict(parse.parse_qsl(raw))
if 'cmd' not in self.raw:
raise DivaRequestParseException(f"cmd not in request data {self.raw}")
self.cmd = raw['cmd']
if 'req_id' not in self.raw:
raise DivaRequestParseException(f"req_id not in request data {self.raw}")
self.req_id = raw['req_id']
class BaseResponse:
def __init__(self, cmd_id: str, req_id: int) -> None:
self.cmd = cmd_id
self.req_id = req_id
self.stat = "ok"
def make(self) -> str:
all_vars = vars(self)
all_vars.pop('cmd')
all_vars.pop('req_id')
ret = f"cmd={self.cmd}&req_id={self.req_id}"
ret += parse.urlencode(all_vars, doseq=True, quote_via=parse.quote)
return ret