Skip to content
This repository was archived by the owner on Jun 21, 2025. It is now read-only.

Commit 5348441

Browse files
Merge pull request #13 from andrewthetechie/add-ips-to-serializer
feat: serialize ipnetworks
2 parents 6fdf1ea + 837a9c1 commit 5348441

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

pydantic_aioredis/abstract.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22
import json
33
from datetime import date
44
from datetime import datetime
5+
from ipaddress import IPv4Address
6+
from ipaddress import IPv4Network
7+
from ipaddress import IPv6Address
8+
from ipaddress import IPv6Network
59
from typing import Any
610
from typing import Dict
711
from typing import List
@@ -69,6 +73,10 @@ def json_default(obj: Any) -> str:
6973

7074
if isinstance(obj, (datetime, date)):
7175
return obj.isoformat()
76+
77+
if isinstance(obj, (IPv4Network, IPv4Address, IPv6Network, IPv6Address)):
78+
return str(obj)
79+
7280
raise TypeError("Type %s not serializable" % type(obj))
7381

7482
@classmethod

test/test_pydantic_aioredis.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""Tests for the redis orm"""
22
from datetime import date
3+
from ipaddress import ip_network
4+
from ipaddress import IPv4Network
35
from random import randint
46
from random import sample
57
from typing import List
@@ -58,6 +60,12 @@ class TestModelWithNone(Model):
5860
optional_field: Optional[str]
5961

6062

63+
class TestModelWithIP(Model):
64+
_primary_key_field = "name"
65+
name: str
66+
ip_network: IPv4Network
67+
68+
6169
extended_books = [
6270
ExtendedBook(**book.dict(), editions=sample(editions, randint(0, len(editions))))
6371
for book in books
@@ -69,6 +77,11 @@ class TestModelWithNone(Model):
6977
TestModelWithNone(name="test2"),
7078
]
7179

80+
test_ip_models = [
81+
TestModelWithIP(name="test", ip_network=ip_network("10.10.0.0/24")),
82+
TestModelWithIP(name="test2", ip_network=ip_network("192.168.0.0/16")),
83+
]
84+
7285

7386
@pytest.fixture()
7487
async def redis_store(redis_server):
@@ -81,6 +94,7 @@ async def redis_store(redis_server):
8194
store.register_model(Book)
8295
store.register_model(ExtendedBook)
8396
store.register_model(TestModelWithNone)
97+
store.register_model(TestModelWithIP)
8498
yield store
8599
keys = [f"book_%&_{book.title}" for book in books]
86100
await store.redis_store.delete(*keys)
@@ -126,6 +140,7 @@ def test_store_model(redis_store):
126140
(pytest.lazy_fixture("redis_store"), books, Book),
127141
(pytest.lazy_fixture("redis_store"), extended_books, ExtendedBook),
128142
(pytest.lazy_fixture("redis_store"), test_models, TestModelWithNone),
143+
(pytest.lazy_fixture("redis_store"), test_ip_models, TestModelWithIP),
129144
]
130145

131146

0 commit comments

Comments
 (0)