2024-06-05 09:11:37 +01:00
|
|
|
# © Crown-owned copyright 2024, Defence Science and Technology Laboratory UK
|
2024-03-11 20:10:08 +00:00
|
|
|
from typing import Dict, ForwardRef, List, Literal, Union
|
2024-03-08 12:42:22 +00:00
|
|
|
|
2024-06-25 11:04:52 +01:00
|
|
|
from pydantic import BaseModel, ConfigDict, StrictBool # , validate_call
|
2024-03-08 14:58:34 +00:00
|
|
|
|
2024-05-31 13:53:18 +01:00
|
|
|
RequestFormat = List[Union[str, int, float, Dict]]
|
2024-03-11 20:10:08 +00:00
|
|
|
|
2024-03-08 14:58:34 +00:00
|
|
|
RequestResponse = ForwardRef("RequestResponse")
|
|
|
|
|
"""This makes it possible to type-hint RequestResponse.from_bool return type."""
|
2024-03-08 12:42:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class RequestResponse(BaseModel):
|
|
|
|
|
"""Schema for generic request responses."""
|
|
|
|
|
|
2024-03-09 20:47:57 +00:00
|
|
|
model_config = ConfigDict(extra="forbid", strict=True)
|
2024-03-08 12:42:22 +00:00
|
|
|
"""Cannot have extra fields in the response. Anything custom goes into the data field."""
|
|
|
|
|
|
2024-03-08 14:58:34 +00:00
|
|
|
status: Literal["pending", "success", "failure", "unreachable"] = "pending"
|
2024-03-08 12:42:22 +00:00
|
|
|
"""
|
|
|
|
|
What is the current status of the request:
|
|
|
|
|
- pending - the request has not been received yet, or it has been received but it's still being processed.
|
2024-03-08 14:58:34 +00:00
|
|
|
- success - the request has been received and executed successfully.
|
|
|
|
|
- failure - the request has been received and attempted, but execution failed.
|
|
|
|
|
- unreachable - the request could not reach it's intended target, either because it doesn't exist or the target
|
|
|
|
|
is off.
|
2024-03-08 12:42:22 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
data: Dict = {}
|
|
|
|
|
"""Catch-all place to provide any additional data that was generated as a response to the request."""
|
|
|
|
|
# TODO: currently, status and data have default values, because I don't want to interrupt existing functionality too
|
|
|
|
|
# much. However, in the future we might consider making them mandatory.
|
2024-03-08 14:58:34 +00:00
|
|
|
|
|
|
|
|
@classmethod
|
2024-06-25 11:04:52 +01:00
|
|
|
# @validate_call # this slows down execution quite a bit.
|
2024-03-09 20:47:57 +00:00
|
|
|
def from_bool(cls, status_bool: StrictBool) -> RequestResponse:
|
2024-03-08 14:58:34 +00:00
|
|
|
"""
|
|
|
|
|
Construct a basic request response from a boolean.
|
|
|
|
|
|
|
|
|
|
True maps to a success status. False maps to a failure status.
|
|
|
|
|
|
|
|
|
|
:param status_bool: Whether to create a successful response
|
|
|
|
|
:type status_bool: bool
|
|
|
|
|
"""
|
|
|
|
|
if status_bool is True:
|
|
|
|
|
return cls(status="success", data={})
|
|
|
|
|
elif status_bool is False:
|
|
|
|
|
return cls(status="failure", data={})
|