Skip to content

Commit afdcf5c

Browse files
committed
Add support for ipaddress objects in JSONEncoder
1 parent 337ba21 commit afdcf5c

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

rest_framework/utils/encoders.py

+10
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import contextlib
66
import datetime
77
import decimal
8+
import ipaddress
89
import json # noqa
910
import uuid
1011

@@ -45,6 +46,15 @@ def default(self, obj):
4546
return float(obj)
4647
elif isinstance(obj, uuid.UUID):
4748
return str(obj)
49+
elif isinstance(obj, (
50+
ipaddress.IPv4Address,
51+
ipaddress.IPv6Address,
52+
ipaddress.IPv4Network,
53+
ipaddress.IPv6Network,
54+
ipaddress.IPv4Interface,
55+
ipaddress.IPv6Interface)
56+
):
57+
return str(obj)
4858
elif isinstance(obj, QuerySet):
4959
return tuple(obj)
5060
elif isinstance(obj, bytes):

tests/test_encoders.py

+43
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import ipaddress
12
from datetime import date, datetime, timedelta, timezone
23
from decimal import Decimal
34
from uuid import uuid4
@@ -78,6 +79,48 @@ def test_encode_uuid(self):
7879
unique_id = uuid4()
7980
assert self.encoder.default(unique_id) == str(unique_id)
8081

82+
def test_encode_ipaddress_ipv4address(self):
83+
"""
84+
Tests encoding ipaddress IPv4Address object
85+
"""
86+
obj = ipaddress.IPv4Address("192.168.1.1")
87+
assert self.encoder.default(obj) == str(obj)
88+
89+
def test_encode_ipaddress_ipv6address(self):
90+
"""
91+
Tests encoding ipaddress IPv6Address object
92+
"""
93+
obj = ipaddress.IPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334")
94+
assert self.encoder.default(obj) == str(obj)
95+
96+
def test_encode_ipaddress_ipv4network(self):
97+
"""
98+
Tests encoding ipaddress IPv4Network object
99+
"""
100+
obj = ipaddress.IPv4Network("192.0.2.8/29")
101+
assert self.encoder.default(obj) == str(obj)
102+
103+
def test_encode_ipaddress_ipv6network(self):
104+
"""
105+
Tests encoding ipaddress IPv4Network object
106+
"""
107+
obj = ipaddress.IPv6Network("2001:4860:0000::0000/32")
108+
assert self.encoder.default(obj) == str(obj)
109+
110+
def test_encode_ipaddress_ipv4interface(self):
111+
"""
112+
Tests encoding ipaddress IPv4Interface object
113+
"""
114+
obj = ipaddress.IPv4Interface("192.0.2.8/29")
115+
assert self.encoder.default(obj) == str(obj)
116+
117+
def test_encode_ipaddress_ipv6interface(self):
118+
"""
119+
Tests encoding ipaddress IPv4Network object
120+
"""
121+
obj = ipaddress.IPv6Interface("2001:4860:4860::8888/32")
122+
assert self.encoder.default(obj) == str(obj)
123+
81124
@pytest.mark.skipif(not coreapi, reason='coreapi is not installed')
82125
def test_encode_coreapi_raises_error(self):
83126
"""

0 commit comments

Comments
 (0)