| 1 |
from enum import Enum |
| 2 |
from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network |
| 3 |
from typing import Any, FrozenSet, Generic, TypeVar |
| 4 |
|
| 5 |
from django.core.serializers.json import DjangoJSONEncoder |
| 6 |
from django.http import JsonResponse |
| 7 |
from pydantic import AnyUrl, BaseModel |
| 8 |
from pydantic_core import Url |
| 9 |
|
| 10 |
__all__ = [ |
| 11 |
"NinjaJSONEncoder", |
| 12 |
"Response", |
| 13 |
"Status", |
| 14 |
"codes_1xx", |
| 15 |
"codes_2xx", |
| 16 |
"codes_3xx", |
| 17 |
"codes_4xx", |
| 18 |
"codes_5xx", |
| 19 |
] |
| 20 |
|
| 21 |
|
| 22 |
T = TypeVar("T") |
| 23 |
|
| 24 |
|
| 25 |
class Status(Generic[T]): |
| 26 |
"""Return a response with an explicit HTTP status code. |
| 27 |
|
| 28 |
Usage: |
| 29 |
return Status(200, {"key": "value"}) |
| 30 |
return Status(204, None) |
| 31 |
""" |
| 32 |
|
| 33 |
__slots__ = ("status_code", "value") |
| 34 |
|
| 35 |
def __init__(self, status_code: int, value: T): |
| 36 |
self.status_code = status_code |
| 37 |
self.value = value |
| 38 |
|
| 39 |
|
| 40 |
class NinjaJSONEncoder(DjangoJSONEncoder): |
| 41 |
def default(self, o: Any) -> Any: |
| 42 |
if isinstance(o, BaseModel): |
| 43 |
return o.model_dump() |
| 44 |
if isinstance(o, (Url, AnyUrl)): |
| 45 |
return str(o) |
| 46 |
if isinstance(o, (IPv4Address, IPv4Network, IPv6Address, IPv6Network)): |
| 47 |
return str(o) |
| 48 |
if isinstance(o, Enum): |
| 49 |
return str(o) |
| 50 |
return super().default(o) |
| 51 |
|
| 52 |
|
| 53 |
class Response(JsonResponse): |
| 54 |
def __init__(self, data: Any, **kwargs: Any) -> None: |
| 55 |
super().__init__(data, encoder=NinjaJSONEncoder, safe=False, **kwargs) |
| 56 |
|
| 57 |
|
| 58 |
def resp_codes(from_code: int, to_code: int) -> FrozenSet[int]: |
| 59 |
return frozenset(range(from_code, to_code + 1)) |
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
codes_1xx = resp_codes(100, 101) |
| 64 |
codes_2xx = resp_codes(200, 206) |
| 65 |
codes_3xx = resp_codes(300, 308) |
| 66 |
codes_4xx = resp_codes(400, 412) | frozenset({416, 418, 425, 429, 451}) |
| 67 |
codes_5xx = resp_codes(500, 504) |