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.Any because 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.

__call__() → dict[TypeVar, TypeForm[Any]][source]#

Run the inference.

Returns:

Mapping of type vars to its inferenced values. It can still be a type variable, if no real values are provided.

dmr.types.safe_typevar(typevar_name: str, *, stacklevel: int = 1, globalns: dict[str, Any] | None = None) → Any[source]#

Typing utility to allow passing typing.TypeVar safely.

By default mypy and 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 globals namespace. 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 dispatch method.

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 MyController to 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 decorator

Danger

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 use endpoint_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 decorator

Warning

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_required will 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

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.