-
Notifications
You must be signed in to change notification settings - Fork 3
Refactor JSON parsing middleware into helper #42
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 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 hidden or 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 hidden or 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,112 @@ | ||
| """Utilities for middleware response handling.""" | ||
|
|
||
| import json | ||
| import re | ||
| from abc import ABC, abstractmethod | ||
| from typing import Any, Optional | ||
|
|
||
| from starlette.datastructures import Headers, MutableHeaders | ||
| from starlette.requests import Request | ||
| from starlette.types import ASGIApp, Message, Receive, Scope, Send | ||
|
|
||
|
|
||
| class JsonResponseMiddleware(ABC): | ||
| """Base class for middleware that transforms JSON response bodies.""" | ||
|
|
||
| app: ASGIApp | ||
| json_content_type_expr: str = ( | ||
| r"application/vnd\.oai\.openapi\+json;.*|application/json|application/geo\+json" | ||
| ) | ||
|
|
||
| @abstractmethod | ||
| def should_transform_response(self, request: Request) -> bool: | ||
| """ | ||
| Determine if this request's response should be transformed. | ||
|
|
||
| Args: | ||
| request: The incoming request | ||
|
|
||
| Returns | ||
| ------- | ||
| bool: True if the response should be transformed | ||
| """ | ||
| return bool( | ||
| re.match(self.json_content_type_expr, request.headers.get("accept", "")) | ||
| ) | ||
|
|
||
| @abstractmethod | ||
| def transform_json(self, data: Any) -> Any: | ||
| """ | ||
| Transform the JSON data. | ||
|
|
||
| Args: | ||
| data: The parsed JSON data | ||
|
|
||
| Returns | ||
| ------- | ||
| The transformed JSON data | ||
| """ | ||
| pass | ||
|
|
||
| async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: | ||
| """Process the request/response.""" | ||
| if scope["type"] != "http": | ||
| return await self.app(scope, receive, send) | ||
|
|
||
| request = Request(scope) | ||
| if not self.should_transform_response(request): | ||
| return await self.app(scope, receive, send) | ||
|
|
||
| start_message: Optional[Message] = None | ||
| body = b"" | ||
| not_json = False | ||
|
|
||
| async def process_message(message: Message) -> None: | ||
| nonlocal start_message | ||
| nonlocal body | ||
| nonlocal not_json | ||
| if message["type"] == "http.response.start": | ||
| # Delay sending start message until we've processed the body | ||
| if not re.match( | ||
| self.json_content_type_expr, | ||
| Headers(scope=message).get("content-type", ""), | ||
| ): | ||
| not_json = True | ||
| return await send(message) | ||
| start_message = message | ||
| return | ||
| elif message["type"] != "http.response.body" or not_json: | ||
| return await send(message) | ||
|
|
||
| body += message["body"] | ||
|
|
||
| # Skip body chunks until all chunks have been received | ||
| if message.get("more_body"): | ||
| return | ||
|
|
||
| headers = MutableHeaders(scope=start_message) | ||
|
|
||
| # Transform the JSON body | ||
| if body: | ||
| data = json.loads(body) | ||
| transformed = self.transform_json(data) | ||
| body = json.dumps(transformed).encode() | ||
|
|
||
| # Update content-length header | ||
| headers["content-length"] = str(len(body)) | ||
| assert start_message, "Expected start_message to be set" | ||
| start_message["headers"] = [ | ||
| (key.encode(), value.encode()) for key, value in headers.items() | ||
| ] | ||
|
|
||
| # Send response | ||
| await send(start_message) | ||
| await send( | ||
| { | ||
| "type": "http.response.body", | ||
| "body": body, | ||
| "more_body": False, | ||
| } | ||
| ) | ||
|
|
||
| return await self.app(scope, receive, process_message) | ||
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.
@alukach you may also add
application/schema+json(queryables)