-
-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
refactor: post serialization simplified #211
Open
wax911
wants to merge
2
commits into
develop
Choose a base branch
from
refactor/post-serialization-simplified
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,40 @@ | ||
import logging | ||
|
||
from typing import Dict, Type | ||
from serde import Model | ||
from uplink import error_handler | ||
|
||
from core.schemas import CommonSchema | ||
|
||
|
||
@error_handler(requires_consumer=True) | ||
def raise_api_error(consumer, exc_type=None, exc_val=None, exc_tb=None): | ||
logger = logging.getLogger("django") | ||
logger.warning(f"API error occurred -> exc_type: {exc_type} exc_val: {exc_val} exc_tb: {exc_tb}") | ||
logger.warning( | ||
f"API error occurred -> exc_type: {exc_type} exc_val: {exc_val} exc_tb: {exc_tb}" | ||
) | ||
|
||
|
||
def to_model(model_class: Type[Model]): | ||
""" | ||
Decorator that adds functionality to schema classes to convert dict to model instance. | ||
|
||
Args: | ||
model_class: The model class to convert the dictionary data into | ||
""" | ||
|
||
def decorator(schema_class: CommonSchema): | ||
def on_post_serialization( | ||
self: CommonSchema, data: Dict, many: bool, **kwargs | ||
) -> Model: | ||
self._logger.debug(f"Executing post_load for {model_class.__name__}") | ||
try: | ||
model = model_class.from_dict(data) | ||
return model | ||
except Exception as e: | ||
self._logger.error(f"Conversion from dictionary failed", exc_info=e) | ||
raise e | ||
|
||
schema_class._on_post_load = on_post_serialization | ||
return schema_class | ||
|
||
return decorator |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,7 +3,7 @@ | |
from logging import Logger | ||
from typing import Any, Optional, Dict, Union, cast | ||
|
||
from marshmallow import Schema | ||
from marshmallow import Schema, post_load | ||
from marshmallow.schema import SchemaMeta | ||
from marshmallow.types import StrSequenceOrSet | ||
|
||
|
@@ -18,6 +18,7 @@ def __init__(self, *, only: Optional[StrSequenceOrSet] = None, exclude: StrSeque | |
super().__init__(only=only, exclude=exclude, many=many, context=context, load_only=load_only, | ||
dump_only=dump_only, partial=partial, unknown=unknown) | ||
|
||
@post_load() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If we don't add |
||
def _on_post_load(self, data, many, **kwargs) -> Any: | ||
pass | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import pytest | ||
import marshmallow | ||
import serde | ||
import serde.fields | ||
|
||
from core.decorators import to_model | ||
from core.schemas import CommonSchema | ||
|
||
class TestModel(serde.Model): | ||
name = serde.fields.Str() | ||
value = serde.fields.Int() | ||
|
||
@to_model(TestModel) | ||
class TestSchema(CommonSchema): | ||
name = marshmallow.fields.String(required=True) | ||
value = marshmallow.fields.Integer(required=True) | ||
|
||
|
||
class TestDecorator: | ||
def test_successful_conversion(self): | ||
test_data = {"name": "test", "value": 123} | ||
schema = TestSchema() | ||
|
||
result = schema.load(test_data) | ||
|
||
assert isinstance(result, TestModel) | ||
assert result.name == "test" | ||
assert result.value == 123 | ||
|
||
def test_failed_conversion(self): | ||
test_data = {"name": "test"} | ||
schema = TestSchema() | ||
|
||
with pytest.raises(Exception): | ||
schema.load(test_data) | ||
|
||
def test_multiple_schema_instances(self): | ||
test_data = {"name": "test", "value": 123} | ||
schema1 = TestSchema() | ||
schema2 = TestSchema() | ||
|
||
result1 = schema1.load(test_data) | ||
result2 = schema2.load(test_data) | ||
|
||
assert isinstance(result1, TestModel) | ||
assert isinstance(result2, TestModel) | ||
assert result1.name == result2.name | ||
assert result1.value == result2.value | ||
|
||
def test_successful_conversion_with_json(self): | ||
test_data = '{"name": "test", "value": 123}' | ||
schema = TestSchema() | ||
|
||
result = schema.loads(test_data) | ||
|
||
assert isinstance(result, TestModel) | ||
assert result.name == "test" | ||
assert result.value == 123 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Basically redefine the contract
_on_post_load
by assigning it an implementation