-
-
Notifications
You must be signed in to change notification settings - Fork 167
/
Copy path_utils.py
92 lines (70 loc) · 2.68 KB
/
_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
from typing import Optional, Type, Any, Tuple
from fastapi import Depends, HTTPException
from pydantic import create_model
from ._types import T, PAGINATION, PYDANTIC_SCHEMA
class AttrDict(dict): # type: ignore
def __init__(self, *args, **kwargs) -> None: # type: ignore
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
def get_pk_type(schema: Type[PYDANTIC_SCHEMA], pk_field: str = "id") -> Any:
try:
return schema.__fields__[pk_field].type_
except KeyError:
return int
def create_schema_default_factory(
schema_cls: Type[T], create_schema_instance: T, pk_field_name: str = "id"
) -> Tuple[T, bool]:
"""
Is used to check for default_factory for the pk on a Schema,
passing the CreateSchema values into the Schema if a
default_factory on the pk exists
"""
if callable(schema_cls.__fields__[pk_field_name].default_factory):
return schema_cls(**create_schema_instance.dict()), True
else:
return create_schema_instance, False
def schema_factory(
schema_cls: Type[T], pk_field_name: str = "id", name: str = "Create"
) -> Type[T]:
"""
Is used to create a CreateSchema which does not contain pk
"""
fields = {
f.name: (f.type_, ...)
for f in schema_cls.__fields__.values()
if f.name != pk_field_name
}
name = schema_cls.__name__ + name
schema: Type[T] = create_model(__model_name=name, **fields) # type: ignore
return schema
def create_query_validation_exception(field: str, msg: str) -> HTTPException:
return HTTPException(
422,
detail={
"detail": [
{"loc": ["query", field], "msg": msg, "type": "type_error.integer"}
]
},
)
def pagination_factory(max_limit: Optional[int] = None) -> Any:
"""
Created the pagination dependency to be used in the router
"""
def pagination(skip: int = 0, limit: Optional[int] = max_limit) -> PAGINATION:
if skip < 0:
raise create_query_validation_exception(
field="skip",
msg="skip query parameter must be greater or equal to zero",
)
if limit is not None:
if limit <= 0:
raise create_query_validation_exception(
field="limit", msg="limit query parameter must be greater then zero"
)
elif max_limit and max_limit < limit:
raise create_query_validation_exception(
field="limit",
msg=f"limit query parameter must be less then {max_limit}",
)
return {"skip": skip, "limit": limit}
return Depends(pagination)