-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathshared.py
More file actions
33 lines (27 loc) · 1 KB
/
shared.py
File metadata and controls
33 lines (27 loc) · 1 KB
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
from typing import Any
from pydantic import (
AnyUrl,
BaseModel,
ConfigDict,
SerializerFunctionWrapHandler,
model_serializer,
)
from starlette.datastructures import URL
class Link(BaseModel):
href: AnyUrl
rel: str
type: str | None = None
title: str | None = None
method: str | None = None
headers: dict[str, str | list[str]] | None = None
body: Any = None
model_config = ConfigDict(extra="allow")
# redefining init is a hack to get str type to validate for `href`,
# as str is ultimately coerced into an AnyUrl automatically anyway
def __init__(self, href: AnyUrl | URL | str, **kwargs: Any) -> None:
super().__init__(href=str(href), **kwargs)
# overriding the default serialization to filter None field values from
# dumped json
@model_serializer(mode="wrap", when_used="json")
def serialize(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
return {k: v for k, v in handler(self).items() if v is not None}