Skip to content

Instantly share code, notes, and snippets.

@jlucasoliveira
Last active July 19, 2021 16:50
Show Gist options
  • Save jlucasoliveira/ecba6c325eca3d7fb6c77537555518ec to your computer and use it in GitHub Desktop.
Save jlucasoliveira/ecba6c325eca3d7fb6c77537555518ec to your computer and use it in GitHub Desktop.
Auto schema on viewset without override all methods
from typing import Callable, List, ClassVar, Union
from rest_framework.views import APIView
# Inspired on https://stackoverflow.com/q/64185352
def auto_schema_once(*, names: Union[List[str], str], decorator: Callable, schemas: dict) -> Callable:
if names == "__all__":
names = ["create", "list", "retrieve", "destroy", "update", "partial_update"]
def _decorator(cls: ClassVar[APIView]) -> ClassVar[APIView]:
for name in names:
method = getattr(cls, name)
schema = schemas[name] if name in schemas else {}
setattr(cls, name, decorator(**schema)(method))
return cls
return _decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment