Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
🔨 Class-Based Parsers and Serializers (#96)
- Loading branch information
Showing
13 changed files
with
357 additions
and
126 deletions.
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,2 +1,2 @@ | ||
from .blueprint import APIBlueprint | ||
from .jeroboam import APIBlueprint | ||
from .jeroboam import Jeroboam |
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 was deleted.
Oops, something went wrong.
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,50 +1,84 @@ | ||
import traceback | ||
import typing as t | ||
from functools import wraps | ||
from typing import Any | ||
from typing import Callable | ||
from typing import Dict | ||
from typing import Optional | ||
from typing import TypeVar | ||
|
||
from flask import Response | ||
from flask.globals import current_app | ||
from pydantic import BaseModel | ||
from typing_extensions import ParamSpec | ||
|
||
from .exceptions import ServerError | ||
from .typing import JeroboamResponseReturnValue | ||
from .typing import JeroboamRouteCallable | ||
from .typing import ResponseModel | ||
|
||
|
||
# from .typing import TypedParams | ||
# from .utils import get_typed_return_annotation | ||
|
||
|
||
P = ParamSpec("P") | ||
R = TypeVar("R") | ||
|
||
|
||
def _prepare_response(result: BaseModel, status: int = 200) -> Response: | ||
"""Wraps simple Response initialisation.""" | ||
return Response(result.json(), mimetype="application/json", status=status) | ||
class Serializer: | ||
"""A Serializer Class for Flask-Jeroboam.""" | ||
|
||
def __init__(self, func: Callable, options: Dict[str, Any]): | ||
self.response_model = self.get_response_model(func, options) | ||
|
||
def get_response_model( | ||
self, func: Callable, options: Dict[str, Any] | ||
) -> Optional[ResponseModel]: | ||
"""Extract the Response Model from view function. | ||
It takes it either explicitly from the options | ||
or from return type of the view function if it is | ||
a pydantic BaseModel. | ||
""" | ||
response_model = options.pop("response_model", None) | ||
"""if response_model is None: | ||
return_annotation = get_typed_return_annotation(func) | ||
if issubclass(return_annotation, BaseModel): | ||
response_model = return_annotation """ | ||
return response_model | ||
|
||
def serializer(response_model: t.Type[BaseModel], status_code: int = 200): | ||
"""Parameterized decorator for view functions.""" | ||
def __bool__(self) -> bool: | ||
"""Return True if the Serializer has a Response Model.""" | ||
return bool(self.response_model) | ||
|
||
def _prepare_response(self, result: BaseModel, status: int = 200) -> Response: | ||
"""Wraps simple Response initialisation.""" | ||
return Response(result.json(), status=status, mimetype="application/json") | ||
|
||
def __call__( | ||
self, func: JeroboamRouteCallable, status_code: int | ||
) -> JeroboamRouteCallable: | ||
"""Return a view funcion.""" | ||
|
||
def serialize_decorator( | ||
func: Callable[P, t.Union[R, Response]] | ||
) -> Callable[P, t.Union[R, Response]]: | ||
@wraps(func) | ||
def inner(*args: P.args, **kwargs: P.kwargs) -> t.Union[R, Response]: | ||
response = func(*args, **kwargs) | ||
if isinstance(response, dict): | ||
def wrapper(*args, **kwargs) -> JeroboamResponseReturnValue: | ||
response = current_app.ensure_sync(func)(*args, **kwargs) | ||
if self.response_model is None: # pragma: no cover | ||
return response | ||
elif isinstance(response, dict): | ||
try: | ||
validated_response = response_model(**response) | ||
validated_response = self.response_model(**response) | ||
except ValueError as e: | ||
raise ServerError( | ||
msg="Internal server error", | ||
error=e, | ||
trace=traceback.format_exc(), | ||
context=f"Trying to validate result with value {response}.", | ||
) from e | ||
return _prepare_response(validated_response, status_code) | ||
elif isinstance(response, response_model): | ||
return _prepare_response(response, status_code) | ||
return self._prepare_response(validated_response, status_code) | ||
elif isinstance(response, self.response_model): | ||
return self._prepare_response(response, status_code) | ||
else: | ||
return response | ||
|
||
return inner | ||
|
||
return serialize_decorator | ||
return wrapper |
This file was deleted.
Oops, something went wrong.
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.