Browse Source

feat(py): Add `method_dispatch` helper for splitting endpoints (#45667)

Evan Purkhiser 2 years ago
parent
commit
0c225ed01b
1 changed files with 18 additions and 0 deletions
  1. 18 0
      src/sentry/api/utils.py

+ 18 - 0
src/sentry/api/utils.py

@@ -7,6 +7,7 @@ from datetime import timedelta
 from typing import Any, List, Literal, Tuple, overload
 from urllib.parse import urlparse
 
+from django.http import HttpResponseNotAllowed
 from django.utils import timezone
 from rest_framework.request import Request
 
@@ -266,3 +267,20 @@ def customer_domain_path(path: str) -> str:
         if updated != path:
             return updated
     return path
+
+
+def method_dispatch(**dispatch_mapping):  # type: ignore[no-untyped-def]
+    """
+    Dispatches a incoming request to a different handler based on the HTTP method
+
+    >>> url('^foo$', method_dispatch(POST = post_handler, GET = get_handler)))
+    """
+
+    def invalid_method(request, *args, **kwargs):  # type: ignore[no-untyped-def]
+        return HttpResponseNotAllowed(dispatch_mapping.keys())
+
+    def dispatcher(request, *args, **kwargs):  # type: ignore[no-untyped-def]
+        handler = dispatch_mapping.get(request.method, invalid_method)
+        return handler(request, *args, **kwargs)
+
+    return dispatcher