Created
June 25, 2023 10:37
-
-
Save danjac/1e3f6d6c7d4f4d90a09d7489fe4f412a to your computer and use it in GitHub Desktop.
Decorator to dispatch to different functions based on HTTP methods
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
def method_dispatcher(view: Callable) -> Callable: | |
"""Dispatch for method. Turns view into decorator so you can do: | |
@method_dispatcher | |
def my_view(request): | |
return HttpResponse() | |
@method_dispatcher("POST", "PUT") | |
def submit(request): | |
... # does whatever on POST or PUT | |
""" | |
view._dispatch_to: list[tuple[Callable, list[str]]] = [] | |
def _dispatch(*methods: str) -> Callable: | |
def _decorator(fn: Callable) -> Callable: | |
view._dispatch_to.append((fn, methods)) | |
return _decorator | |
def _wrapper(request: HttpRequest, *args, **kwargs) -> HttpResponse: | |
for fn, methods in view._dispatch_to: | |
if request.method in methods: | |
return fn(request, *args, **kwargs) | |
return view(request, *args, **kwargs) | |
_wrapper.dispatch = _dispatch | |
return _wrapper | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment