Skip to content

Commit 0635416

Browse files
authored
Merge pull request #9 from RSS-Engineering/alias_fields_fix
fix for pydantic fields with alias
2 parents b239af3 + 60b555f commit 0635416

File tree

4 files changed

+65
-4
lines changed

4 files changed

+65
-4
lines changed

pydanticrud/backends/dynamodb.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,7 @@ def get(self, key):
333333
return self._deserialize_record(resp["Item"])
334334

335335
def save(self, item, condition: Optional[Rule] = None) -> bool:
336-
data = self._serialize_record(item.dict())
336+
data = self._serialize_record(item.dict(by_alias=True))
337337

338338
try:
339339
if condition:

pydanticrud/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def get(cls, *args, **kwargs):
3636

3737
def save(self) -> bool:
3838
# Parse the new obj to trigger validation
39-
self.__class__.parse_obj(self.dict())
39+
self.__class__.parse_obj(self.dict(by_alias=True))
4040

4141
# Maybe we should pass a conditional to the backend but for now the only place that uses it doesn't need it.
4242
return self.__class__.__backend__.save(self)

pyproject.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ python = ">=3.6"
1010
boto3 = "^1.17.112"
1111
rule-engine = "^3.2.0"
1212
pydantic = "^1.8.2"
13-
boto3 = {version = "^1.17.112", optional = true}
1413
dataclasses = {version = "^0.8", python = "3.6"}
1514

1615
[tool.poetry.dev-dependencies]

tests/test_dynamodb.py

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import random
66

77
import docker
8-
from pydantic import BaseModel as PydanticBaseModel
8+
from pydantic import BaseModel as PydanticBaseModel, Field
99
from pydanticrud import BaseModel, DynamoDbBackend, ConditionCheckFailed
1010
import pytest
1111
from pydanticrud.exceptions import DoesNotExist
@@ -39,6 +39,19 @@ class Config:
3939
global_indexes = {"by-id": ("id",)}
4040

4141

42+
class AliasKeyModel(BaseModel):
43+
id: int
44+
value: int
45+
name: str
46+
type_: str = Field(alias="type")
47+
48+
class Config:
49+
title = "AliasTitle123"
50+
hash_key = "name"
51+
backend = DynamoDbBackend
52+
endpoint = "http://localhost:18002"
53+
54+
4255
class ComplexKeyModel(BaseModel):
4356
account: str
4457
sort_date_key: str
@@ -79,6 +92,17 @@ class Config:
7992
endpoint = "http://localhost:18002"
8093

8194

95+
def alias_model_data_generator(**kwargs):
96+
data = dict(
97+
id=random.randint(0, 100000),
98+
value=random.randint(0, 100000),
99+
name=random_unique_name(),
100+
type="aliasType"
101+
)
102+
data.update(kwargs)
103+
return data
104+
105+
82106
def simple_model_data_generator(**kwargs):
83107
data = dict(
84108
id=random.randint(0, 100000),
@@ -163,6 +187,14 @@ def nested_table(dynamo):
163187
return NestedModel
164188

165189

190+
@pytest.fixture(scope="module")
191+
def alias_table(dynamo):
192+
if not AliasKeyModel.exists():
193+
AliasKeyModel.initialize()
194+
assert AliasKeyModel.exists()
195+
return AliasKeyModel
196+
197+
166198
@pytest.fixture(scope="module")
167199
def simple_query_data(simple_table):
168200
presets = [dict(name="Jerry"), dict(name="Hermione"), dict(), dict(), dict()]
@@ -190,6 +222,18 @@ def complex_query_data(complex_table):
190222
ComplexKeyModel.delete((datum[ComplexKeyModel.Config.hash_key], datum[ComplexKeyModel.Config.range_key]))
191223

192224

225+
@pytest.fixture(scope="module")
226+
def alias_query_data(alias_table):
227+
presets = [dict(name="Jerry"), dict(name="Hermione"), dict(), dict(), dict()]
228+
data = [datum for datum in [alias_model_data_generator(**i) for i in presets]]
229+
for datum in data:
230+
AliasKeyModel.parse_obj(datum).save()
231+
try:
232+
yield data
233+
finally:
234+
for datum in data:
235+
AliasKeyModel.delete(datum["name"])
236+
193237
@pytest.fixture(scope="module")
194238
def nested_query_data(nested_table):
195239
presets = [dict()] * 5
@@ -348,3 +392,21 @@ def test_query_with_nested_model_optional(dynamo, nested_query_data_optional):
348392
res = NestedModel.query(filter_expr=Rule(f"expires <= '{data_by_expires['expires']}'"))
349393
res_data = [m.ticket for m in res]
350394
assert any(elem is None for elem in res_data)
395+
396+
397+
def test_query_alias_save(dynamo):
398+
presets = [dict(name="Jerry"), dict(name="Hermione"), dict(), dict(), dict()]
399+
data = [datum for datum in [alias_model_data_generator(**i) for i in presets]]
400+
AliasKeyModel.initialize()
401+
try:
402+
for datum in data:
403+
AliasKeyModel.parse_obj(datum).save()
404+
except Exception as e:
405+
raise pytest.fail("Failed to save Alias model!")
406+
407+
def test_get_alias_model_data(dynamo, alias_query_data):
408+
data = alias_model_data_generator()
409+
res = AliasKeyModel.get(alias_query_data[0]['name'])
410+
assert res.dict(by_alias=True) == alias_query_data[0]
411+
412+

0 commit comments

Comments
 (0)