lavkach3

Форк
0
/
basic_schemes.py 
230 строк · 6.6 Кб
1
import typing
2
from typing import Optional, List, Any
3

4
from pydantic import BaseModel, UUID4, Field, AliasPath, AliasChoices, types, model_validator, \
5
    BeforeValidator
6
from pydantic.config import JsonDict
7
from pydantic.fields import _EmptyKwargs, computed_field
8
from pydantic_core import PydanticUndefined
9
from enum import Enum
10
from ..schemas.list_schema import GenericListSchema
11

12

13
def validate_bollean(x):
14
    if isinstance(x, list):
15
        if 'on' in x:
16
            return True
17
        else:
18
            return False
19
    if isinstance(x, str):
20
        if x == 'on':
21
            return True
22
        else:
23
            return False
24
    return x
25

26

27
bollean = typing.Annotated[bool, BeforeValidator(validate_bollean)]
28

29

30
class BasicModel(BaseModel):
31
    """
32
     Переопределяем для удобства
33
    """
34

35
    def check_condition(self, condition: tuple):
36
        resolution = False
37
        if len(condition) != 3:
38
            raise ValueError('Неверное количество аргументов')
39
        field1, operator, field2 = condition
40
        match operator:
41
            case '==':
42
                ...
43
            case '!=':
44
                fieldinfo = self.model_fields.get(field1)
45
                if fieldinfo is None:
46
                    raise ValueError(f'Неверное имя поля {field1}')
47
                annotation = fieldinfo.annotation
48
                field = getattr(self, field1)
49
                if isinstance(field, Enum):
50
                    normalized_value = annotation(field2.lower())
51
                else:
52
                    normalized_value = field2
53
                if field != normalized_value:
54
                    resolution = True
55
            case '!=':
56
                ...
57
            case '>':
58
                ...
59
            case '>=':
60
                ...
61
            case '<':
62
                ...
63
            case '<=':
64
                ...
65
            case 'in':
66
                ...
67
            case 'not in':
68
                ...
69
        return resolution
70

71
    # def model_post_init(self, __context):
72
    #     if hasattr(self.Config, 'readonly'):
73
    #         readonly = self.Config.readonly
74
    #         if isinstance(readonly, bool):
75
    #             for field_name, field in self.model_fields.items():
76
    #                 field.json_schema_extra = {'readonly': True}
77
    #         elif isinstance(readonly, list):
78
    #             for condition in readonly:
79
    #                 resolution = self.check_condition(condition)
80

81
    class Config:
82
        extra = 'allow'
83
        from_attributes = True
84

85

86
_Unset: Any = PydanticUndefined
87

88

89
def BasicField(
90
        default: Any = PydanticUndefined,
91
        *,
92
        #####
93
        model: str | None = None,  # Имя модели
94
        readonly: bool | list = False,  # Только на чтение (всегда) или одно из условий  например
95
        # [('status','==', 'CONFIRMED')]
96
        table: bool = False,  # Показывать в таблице
97
        ####
98
        default_factory: typing.Callable[[], Any] | None = _Unset,
99
        alias: str | None = _Unset,
100
        alias_priority: int | None = _Unset,
101
        validation_alias: str | AliasPath | AliasChoices | None = _Unset,
102
        serialization_alias: str | None = _Unset,
103
        title: str | None = _Unset,
104
        description: str | None = _Unset,
105
        examples: list[Any] | None = _Unset,
106
        exclude: bool | None = _Unset,
107
        discriminator: str | types.Discriminator | None = _Unset,
108
        json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = _Unset,
109
        frozen: bool | None = _Unset,
110
        validate_default: bool | None = _Unset,
111
        repr: bool = _Unset,
112
        init: bool | None = _Unset,
113
        init_var: bool | None = _Unset,
114
        kw_only: bool | None = _Unset,
115
        pattern: str | None = _Unset,
116
        strict: bool | None = _Unset,
117
        gt: float | None = _Unset,
118
        ge: float | None = _Unset,
119
        lt: float | None = _Unset,
120
        le: float | None = _Unset,
121
        multiple_of: float | None = _Unset,
122
        allow_inf_nan: bool | None = _Unset,
123
        max_digits: int | None = _Unset,
124
        decimal_places: int | None = _Unset,
125
        min_length: int | None = _Unset,
126
        max_length: int | None = _Unset,
127
        union_mode: typing.Literal['smart', 'left_to_right'] = _Unset,
128
        **extra: typing.Unpack[_EmptyKwargs],
129
):
130
    """
131
    Переопределяем для удобства
132
    """
133
    return Field(
134
        default,
135
        table=table,
136
        model=model,
137
        readonly=readonly,
138
        default_factory=default_factory,
139
        alias=alias,
140
        alias_priority=alias_priority,
141
        validation_alias=validation_alias,
142
        serialization_alias=serialization_alias,
143
        title=title,
144
        description=description,
145
        examples=examples,
146
        exclude=exclude,
147
        discriminator=discriminator,
148
        json_schema_extra=json_schema_extra,
149
        frozen=frozen,
150
        validate_default=validate_default,
151
        repr=repr,
152
        init=init,
153
        init_var=init_var,
154
        kw_only=kw_only,
155
        pattern=pattern,
156
        strict=strict,
157
        gt=gt,
158
        ge=ge,
159
        lt=lt,
160
        le=le,
161
        multiple_of=multiple_of,
162
        allow_inf_nan=allow_inf_nan,
163
        max_digits=max_digits,
164
        decimal_places=decimal_places,
165
        min_length=min_length,
166
        max_length=max_length,
167
        union_mode=union_mode,
168
        **extra,
169
    )
170

171

172
class CountrySchema(BaseModel):
173
    lsn: int = 0
174
    id: str
175
    name: str
176
    code: str
177

178

179
class CountryListSchema(GenericListSchema):
180
    data: Optional[List[CountrySchema]]
181

182

183
class LocaleSchema(BaseModel):
184
    lsn: int = 0
185
    id: str = None
186
    language: str
187
    territory: Optional[str | None] = None
188
    display_name: str
189
    english_name: str
190
    language_name: str
191

192

193
class LocaleListSchema(GenericListSchema):
194
    data: Optional[List[LocaleSchema]]
195

196

197
class CurrencySchema(BaseModel):
198
    lsn: int = 0
199
    id: str
200
    name: str
201
    code: str
202

203

204
class CurrencyListSchema(GenericListSchema):
205
    data: Optional[List[CurrencySchema]]
206

207

208
class PhoneSchema(BaseModel):
209
    id: int = 0
210
    country_code: int
211
    country_code_source: int
212
    e164: str
213
    international: str
214
    national: str
215
    national_number: int
216

217

218
class ActionBaseSchame(BaseModel):
219
    id: Optional[UUID4] = Field(default=None, title='Id', hidden=True)
220
    ids: Optional[list[UUID4]] = Field(default=[], title='Ids', hidden=True)
221
    lsn: Optional[int] = Field(default=0, title='Lsn', hidden=True)
222
    vars: Optional[dict] = Field(default={}, title='Vars', hidden=True)
223

224
    class Config:
225
        extra = 'allow'
226

227

228
class ActionRescposeSchema(BaseModel):
229
    status: str
230
    detail: str
231

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.