Created
April 11, 2021 17:54
-
-
Save discrimy/adb523862cd01da559870108a4391429 to your computer and use it in GitHub Desktop.
Generic Django view factory based on required HTTP method
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
from typing import Optional, Any, Callable | |
from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowed | |
View = Callable[..., HttpResponse] | |
def view_dispatch( | |
*, | |
get_view: Optional[View] = None, | |
post_view: Optional[View] = None, | |
put_view: Optional[View] = None, | |
patch_view: Optional[View] = None, | |
) -> View: | |
_allowed_http_methods = [ | |
http_method | |
for (http_method, view) in { | |
'GET': get_view, | |
'POST': post_view, | |
'PUT': put_view, | |
'PATCH': patch_view, | |
}.items() | |
if view is not None | |
] | |
def _options_view() -> HttpResponse: | |
response = HttpResponse() | |
response['Allow'] = ', '.join(_allowed_http_methods) | |
response['Content-Length'] = '0' | |
return response | |
def dispatch( | |
request: HttpRequest, *args: Any, **kwargs: Any | |
) -> HttpResponse: | |
if request.method == 'OPTIONS': | |
return _options_view() | |
if get_view is not None and request.method == 'GET': | |
return get_view(request, *args, **kwargs) | |
if post_view is not None and request.method == 'POST': | |
return post_view(request, *args, **kwargs) | |
if put_view is not None and request.method == 'PUT': | |
return put_view(request, *args, **kwargs) | |
if patch_view is not None and request.method == 'PATCH': | |
return patch_view(request, *args, **kwargs) | |
return HttpResponseNotAllowed(_allowed_http_methods) | |
return dispatch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment