69 lines
3.0 KiB
Python
69 lines
3.0 KiB
Python
import json
|
|
from typing import Any, ClassVar, TypeVar, Dict, Tuple, List
|
|
from pydantic import BaseModel
|
|
|
|
from ErrorHandlers import HTTPExceptionApi
|
|
from ApiLibrary.common.line_number import get_line_number_for_error
|
|
from ApiValidations.Request.base_validations import CrudRecords, PydanticBaseModel
|
|
|
|
|
|
class ValidationParser:
|
|
|
|
def __init__(self, active_validation: BaseModel):
|
|
self.core_validation = active_validation
|
|
self.annotations = active_validation.model_json_schema()
|
|
self.annotations = json.loads(json.dumps(self.annotations))
|
|
self.schema = {}
|
|
self.parse()
|
|
|
|
def parse(self):
|
|
from ApiValidations.Request.base_validations import CrudRecords, PydanticBaseModel
|
|
|
|
properties = dict(self.annotations.get("properties")).items()
|
|
total_class_annotations = {
|
|
**self.core_validation.__annotations__,
|
|
**PydanticBaseModel.__annotations__,
|
|
**CrudRecords.__annotations__,
|
|
}
|
|
for key, value in properties:
|
|
default, required, possible_types = dict(value).get("default", None), True, []
|
|
if dict(value).get("anyOf", None):
|
|
for _ in dict(value).get("anyOf") or []:
|
|
type_opt = json.loads(json.dumps(_))
|
|
if not type_opt.get("type") == "null":
|
|
possible_types.append(type_opt.get("type"))
|
|
field_type = possible_types[0]
|
|
required = False
|
|
else:
|
|
field_type = dict(value).get("type", "string")
|
|
attribute_of_class = total_class_annotations.get(key, None)
|
|
aoc = str(attribute_of_class) if attribute_of_class else None
|
|
if attribute_of_class:
|
|
if aoc in ("<class 'str'>", "typing.Optional[str]"):
|
|
field_type, required = "string", aoc == "<class 'str'>"
|
|
elif aoc in ("<class 'int'>", "typing.Optional[int]"):
|
|
field_type, required = "integer", aoc == "<class 'int'>"
|
|
elif aoc in ("<class 'bool'>", "typing.Optional[bool]"):
|
|
field_type, required = "boolean", aoc == "<class 'bool'>"
|
|
elif aoc in ("<class 'float'>", "typing.Optional[float]"):
|
|
field_type, required = "float", aoc == "<class 'float'>"
|
|
elif aoc in ("<class 'datetime.datetime'>", "typing.Optional[datetime.datetime]"):
|
|
field_type, required = "datetime", aoc == "<class 'datetime.datetime'>"
|
|
self.schema[key] = {
|
|
"type": field_type, "required": required, "default": default
|
|
}
|
|
|
|
|
|
class ValidationModel:
|
|
|
|
def __init__(self, response_model: BaseModel, language_model, language_models):
|
|
self.response_model = response_model
|
|
self.validation = None
|
|
self.headers = language_model
|
|
self.language_models = language_models
|
|
self.get_validation()
|
|
|
|
def get_validation(self) -> Tuple:
|
|
self.headers = self.language_models
|
|
self.validation = ValidationParser(self.response_model).schema
|