Skip to content
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

Provide additional context to marshall. #288

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/marshalls.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,36 @@ the remaining object, functions, attributes and operations, are.
{!> ../docs_src/marshalls/method_field.py !}
```

## Including additional context

In certain scenarios, it is necessary to provide additional context to the marshall. Additional context can be provided by passing a context argument when instantiating the marshall.

**Example**

```python
class UserMarshall(Marshall):
marshall_config: ConfigMarshall = ConfigMarshall(model=User, fields=["name", "email"],)
additional_context: fields.MarshallMethodField = fields.MarshallMethodField(field_type=dict[str, Any])

def get_additional_context(self, instance: edgy.Model) -> dict[str, Any]:
return self.context


data = {"name": "Edgy", "email": "[email protected]"}
marshall = UserMarshall(**data, context={"foo": "bar"})
marshall.model_dump()
```

And the result will be:

```json
{
"name": "Edgy",
"email": "[email protected]",
"additional_context": {"foo": "bar"}
}
```

## `save()`

Since the [Marshall](#marshall) is also a Pydantic base model, the same as Edgy, there may be some
Expand Down
10 changes: 8 additions & 2 deletions edgy/core/marshalls/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ class BaseMarshall(BaseModel, metaclass=MarshallMeta):
__show_pk__: ClassVar[bool] = False
__custom_fields__: ClassVar[dict[str, BaseMarshallField]] = {}

def __init__(self, /, **data: Any) -> None:
super().__init__(**data)
def __init__(self, /, **kwargs: Any) -> None:
_context = kwargs.pop("context", {})
super().__init__(**kwargs)
self._context = _context
self._instance: Model = self._setup()

def _setup(self) -> "Model":
Expand Down Expand Up @@ -54,6 +56,10 @@ def instance(self) -> "Model":
def instance(self, value: "Model") -> None:
self._instance = value

@property
def context(self) -> dict:
return getattr(self, "_context", {})

def _resolve_serializer(self, instance: "Model") -> "BaseMarshall":
"""
Resolve serializer fields and populate them with data from the provided instance.
Expand Down
109 changes: 109 additions & 0 deletions tests/marshalls/test_marshall_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
from typing import Any

import pytest

import edgy
from edgy.core.marshalls import Marshall, fields
from edgy.core.marshalls.config import ConfigMarshall
from edgy.testclient import DatabaseTestClient
from tests.settings import DATABASE_URL

database = DatabaseTestClient(DATABASE_URL)
models = edgy.Registry(database=edgy.Database(database, force_rollback=True))

pytestmark = pytest.mark.anyio


@pytest.fixture(autouse=True, scope="module")
async def create_test_database():
async with database:
await models.create_all()
yield
if not database.drop:
await models.drop_all()


@pytest.fixture(autouse=True, scope="function")
async def rollback_connections():
async with models.database:
yield


class User(edgy.Model):
name: str = edgy.CharField(max_length=100, null=True)
email: str = edgy.EmailField(max_length=100, null=True)
language: str = edgy.CharField(max_length=200, null=True)
description: str = edgy.TextField(max_length=5000, null=True)

class Meta:
registry = models

def get_name(self) -> str:
return f"Details about {self.name}"


class UserMarshall(Marshall):
marshall_config = ConfigMarshall(
model=User, fields=["name", "email", "language", "description"]
)
extra_context: fields.MarshallField = fields.MarshallMethodField(field_type=dict[str, Any])

def get_extra_context(self, instance) -> dict[str, Any]:
return self.context


async def test_marshall_without_context():
data = {
"name": "Edgy",
"email": "[email protected]",
"language": "EN",
"description": "A description",
}

user_marshalled = UserMarshall(**data)

assert user_marshalled.model_dump() == {
"name": "Edgy",
"email": "[email protected]",
"language": "EN",
"description": "A description",
"extra_context": {},
}


async def test_marshall_with_empty_context():
data = {
"name": "Edgy",
"email": "[email protected]",
"language": "EN",
"description": "A description",
}

user_marshalled = UserMarshall(**data, context={})

assert user_marshalled.model_dump() == {
"name": "Edgy",
"email": "[email protected]",
"language": "EN",
"description": "A description",
"extra_context": {},
}


async def test_marshall_with_context():
data = {
"name": "Edgy",
"email": "[email protected]",
"language": "EN",
"description": "A description",
}

user_marshalled = UserMarshall(**data, context={"foo": "bar"})

assert user_marshalled.model_dump() == {
"name": "Edgy",
"email": "[email protected]",
"language": "EN",
"description": "A description",
"extra_context": {"foo": "bar"},
}