Skip to content

Commit

Permalink
passing request and status code to resolve context during response (r…
Browse files Browse the repository at this point in the history
…elated #872 )
  • Loading branch information
vitalik committed Oct 18, 2023
1 parent 08c3168 commit e5e3a4c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
6 changes: 5 additions & 1 deletion ninja/operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,11 @@ def _result_to_response(

resp_object = ResponseObject(result)
# ^ we need object because getter_dict seems work only with model_validate
result = response_model.model_validate(resp_object).model_dump(
validated_object = response_model.model_validate(
resp_object, context={"request": request, "response_status": status}
)

result = validated_object.model_dump(
by_alias=self.by_alias,
exclude_unset=self.exclude_unset,
exclude_defaults=self.exclude_defaults,
Expand Down
35 changes: 34 additions & 1 deletion tests/test_schema_context.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from ninja import Schema
from ninja import NinjaAPI, Schema
from ninja.testing import TestClient


class ResolveWithKWargs(Schema):
Expand All @@ -18,9 +19,41 @@ def resolve_value(obj, context):
return obj["value"] + context["extra"]


class DataWithRequestContext(Schema):
value: dict = None
other: dict = None

@staticmethod
def resolve_value(obj, context):
result = {k: str(v) for k, v in context.items()}
assert "request" in result, "request not in context"
result["request"] = "<request>" # making it static for easier testing
return result


api = NinjaAPI()


@api.post("/resolve_ctx", response=DataWithRequestContext)
def resolve_ctx(request, data: DataWithRequestContext):
return {"other": data.dict()}


client = TestClient(api)


def test_schema_with_context():
obj = ResolveWithKWargs.model_validate({"value": 10}, context={"extra": 10})
assert obj.value == 20

obj = ResolveWithContext.model_validate({"value": 2}, context={"extra": 2})
assert obj.value == 4


def test_request_context():
resp = client.post("/resolve_ctx", json={})
assert resp.status_code == 200, resp.content
assert resp.json() == {
"other": {"value": {"request": "<request>"}, "other": None},
"value": {"request": "<request>", "response_status": "200"},
}

0 comments on commit e5e3a4c

Please sign in to comment.