Skip to content

Commit

Permalink
Merge pull request #1353 from vitalik/grigi/master
Browse files Browse the repository at this point in the history
Add IPNetwork and Url serialisation
  • Loading branch information
vitalik authored Dec 6, 2024
2 parents 5a4cbe7 + 092d4c7 commit ed41ef8
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
7 changes: 5 additions & 2 deletions ninja/responses.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from enum import Enum
from ipaddress import IPv4Address, IPv6Address
from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network
from typing import Any, FrozenSet

from django.core.serializers.json import DjangoJSONEncoder
from django.http import JsonResponse
from pydantic import BaseModel
from pydantic_core import Url

__all__ = [
"NinjaJSONEncoder",
Expand All @@ -21,7 +22,9 @@ class NinjaJSONEncoder(DjangoJSONEncoder):
def default(self, o: Any) -> Any:
if isinstance(o, BaseModel):
return o.model_dump()
if isinstance(o, (IPv4Address, IPv6Address)):
if isinstance(o, Url):
return str(o)
if isinstance(o, (IPv4Address, IPv4Network, IPv6Address, IPv6Network)):
return str(o)
if isinstance(o, Enum):
return str(o)
Expand Down
8 changes: 8 additions & 0 deletions tests/test_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import pytest
from django.http import HttpResponse
from pydantic import BaseModel, ValidationError
from pydantic_core import Url

from ninja import Router
from ninja.responses import Response
Expand Down Expand Up @@ -172,3 +173,10 @@ def test_enum_encoding():
response = Response(data)
response_data = json.loads(response.content)
assert response_data["enum"] == str(data["enum"])


def test_pydantic_url():
data = {"url": Url("https://django-ninja.dev/")}
response = Response(data)
response_data = json.loads(response.content)
assert response_data == {"url": "https://django-ninja.dev/"}

0 comments on commit ed41ef8

Please sign in to comment.