Reusable code#
Utilities#
- dmr.types.Json: TypeAlias = typing.Any#
Recursive type alias for JSON data.
What is JSON? Integers, floats, booleans, strings, list of them and dicts of them, which keys are always strings.
In runtime it is always
typing.Anybecause of the parsing complexity, while in type checking it correctly defined.We don’t recommend using it for anything serious, it is better to define real models instead.
- dmr.types.EMPTY = EMPTY#
Create a unique sentinel object.
name should be the name of the variable to which the return value shall be assigned.
- class dmr.types.AnnotationsContext(*, globalns: Mapping[str, Any] | None = None, localns: Mapping[str, Any] | None = None, include_extras: bool = True, format: Format | None = None)[source]#
Annotation evaluation context.
Use this type to change how controllers resolve type hints of their endpoints.
For example, one can change this function to use
inspect.get_annotations()function. Or to have some pre-defined global names.- __call__(endpoint_func: Callable[[...], Any]) dict[str, Any][source]#
Get the annotations.
- Parameters:
endpoint_func – function with return type annotation.
- Returns:
Function’s parsed and solved return type. Type aliases are unwrapped, so all the callers can work with real types and their metadata.
- Raises:
UnsolvableAnnotationsError – when annotation can’t be solved or when the annotation does not exist.
- class dmr.types.TypeVarInference(to_infer: TypeVar, context: type[Any])[source]#
Inferences type variables to the applied real type values.
Changed in version 0.16.0: PEP 696 type var defaults are now used when the inheritance chain does not provide a real type value.
- dmr.types.safe_typevar(typevar_name: str, *, stacklevel: int = 1, globalns: dict[str, Any] | None = None) Any[source]#
Typing utility to allow passing
typing.TypeVarsafely.By default
mypyand other type-checkers would raise a typing error on a code like this:>>> from typing import TypeVar >>> from http import HTTPStatus >>> from dmr import validate, ResponseSpec >>> _ModelT = TypeVar('_ModelT') >>> validate( ... ResponseSpec( ... # In traditional Python typing spec, it is not allowed ... # to use type var in this context: ... _ModelT, # type: ignore[misc] ... status_code=HTTPStatus.OK, ... ), ... ) <function ...>
But, this function can help with this problem with no type errors:
>>> validate( ... ResponseSpec( ... safe_typevar('_ModelT'), ... status_code=HTTPStatus.OK, ... ), ... ) <function ...>
- Parameters:
typevar_name – TypeVar name to find in the globals.
stacklevel – Levels of function frames to get globals from.
globalns – Explicit
globalsnamespace. Has a higher priority than stacklevel.
- Raises:
KeyError – If typevar_name is not found in globalns.
Added in version 0.14.0.
Decorators#
- dmr.decorators.dispatch_decorator(func: Callable[[...], Any]) Callable[[_TypeT], _TypeT][source]#
Special helper to decorate class-based view’s
dispatchmethod.Use it directly on controllers, like so:
>>> from dmr import Controller >>> from dmr.decorators import dispatch_decorator >>> from dmr.plugins.pydantic import PydanticSerializer >>> from django.contrib.auth.decorators import login_required >>> @dispatch_decorator(login_required()) ... class MyController(Controller[PydanticSerializer]): ... def get(self) -> str: ... return 'Logged in!'
In this example we would require all calls to all methods of
MyControllerto require an existing authentication.It also works for things like: -
django.contrib.auth.decorators.login_not_required()-django.contrib.auth.decorators.user_passes_test()-django.contrib.auth.decorators.permission_required()- and any other default or custom django decoratorDanger
This will return non-json responses, without respecting your spec! Use with caution!
If you want full spec support, use middleware wrappers. You would probably want to use
wrap_middleware()as well. Or useendpoint_decorator().
- dmr.decorators.endpoint_decorator(original_decorator: Callable[[_ViewT], _ViewT]) Callable[[Callable[[_ParamT], _ReturnT]], Callable[[_ParamT], _ReturnT]][source]#
Apply regular Django-styled decorator to a single endpoint.
Use it with “raw” endpoints that return regular data, not
django.http.HttpResponse.Basically, all endpoints that can be decorated with
modify().Example:
>>> from http import HTTPStatus >>> from dmr import Controller, HeaderSpec, modify >>> from dmr.decorators import endpoint_decorator >>> from dmr.plugins.pydantic import PydanticSerializer >>> from django.contrib.auth.decorators import login_required >>> class MyController(Controller[PydanticSerializer]): ... @endpoint_decorator(login_required()) ... @modify( ... extra_responses=[ ... ResponseSpec( ... None, ... status_code=HTTPStatus.FOUND, ... headers={'Location': HeaderSpec()}, ... ), ... ], ... ) ... def get(self) -> str: ... return 'Logged in!'
It also works for things like: -
django.contrib.auth.decorators.login_not_required()-django.contrib.auth.decorators.user_passes_test()-django.contrib.auth.decorators.permission_required()-django.views.decorators.debug.sensitive_post_parameters()- and any other default or custom django decoratorWarning
Be careful with decorators that you apply. They will not escape the response validation, but will return unmodified responses from the original decorators.
For example:
login_requiredwill return a redirect. You can describe it with the extra metadata.
- dmr.decorators.wrap_middleware(middleware: Callable[[Callable[[...], Any]], Callable[[...], Any]], response: ResponseSpec, *responses: ResponseSpec) Callable[[Callable[[HttpResponse], HttpResponse]], DecoratorWithResponses][source]#
Factory function that creates a decorator with pre-configured middleware.
This allows creating reusable decorators with specific middleware and response handling.
- Parameters:
middleware – Django middleware to apply
response – ResponseSpec for the middleware response
responses – Others ResponseSpec
- Returns:
A function that takes a converter and returns a class decorator
[source]1from http import HTTPStatus 2from typing import Final 3 4from django.http import HttpRequest, HttpResponse 5from django.views.decorators.http import condition 6 7from dmr import Controller, HeaderSpec, ResponseSpec 8from dmr.decorators import wrap_middleware 9from dmr.plugins.pydantic import PydanticFastSerializer 10 11# Imitate the version of the catalog in the DB: 12_CATALOG_REVISION: Final = 42 13 14 15def _catalog_etag(request: HttpRequest, **kwargs: object) -> str: 16 return f'"catalog-{_CATALOG_REVISION}"' 17 18 19@wrap_middleware( 20 condition(etag_func=_catalog_etag), 21 ResponseSpec( 22 return_type=None, 23 status_code=HTTPStatus.NOT_MODIFIED, 24 headers={'ETag': HeaderSpec()}, 25 ), 26) 27def catalog_etag_json(response: HttpResponse) -> HttpResponse: 28 """Django's ``304`` response has no ``Content-Type``, set it.""" 29 response['Content-Type'] = 'application/json' 30 return response 31 32 33@catalog_etag_json 34class CatalogController(Controller[PydanticFastSerializer]): 35 """Returns ``304`` when the client already has the latest catalog.""" 36 37 responses = catalog_etag_json.responses 38 39 def get(self) -> list[str]: 40 return ['book', 'pen'] 41 42 43# run: {"controller": "CatalogController", "method": "get", "url": "/api/catalog/", "curl_args": ["-D", "-"]} # noqa: ERA001, E501 44# run: {"controller": "CatalogController", "method": "get", "url": "/api/catalog/", "headers": {"If-None-Match": "\"catalog-42\""}, "curl_args": ["-D", "-"], "assert-error-text": "304", "fail-with-body": false} # noqa: ERA001, E501 45# openapi: {"controller": "CatalogController", "openapi_url": "/docs/openapi.json/"} # noqa: ERA001, E501
Changed in version 0.17.0: Responses that the middleware returns without calling the controller are now validated after the converter, like the responses of endpoints.