djresttoolkit 0.2.0__py3-none-any.whl → 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: djresttoolkit
3
- Version: 0.2.0
3
+ Version: 0.4.0
4
4
  Summary: A collection of Django and DRF utilities to simplify API development.
5
5
  Project-URL: Homepage, https://github.com/shaileshpandit141/djresttoolkit
6
6
  Project-URL: Documentation, https://shaileshpandit141.github.io/djresttoolkit
@@ -8,10 +8,15 @@ src/djresttoolkit/mail/__init__.py,sha256=tB9SdMlhfWQ640q4aobZ0H1c7fTWalpDL2I-on
8
8
  src/djresttoolkit/mail/_email_sender.py,sha256=vvTPZzSAfX2FXHv1IY0ST8dEsq8M4wAxkihm0JbRh1Y,3136
9
9
  src/djresttoolkit/mail/_models.py,sha256=_41pH3xC0jP8SHSty2FkxvRh2_ddKk-4peT11OHcBBE,1462
10
10
  src/djresttoolkit/mail/_types.py,sha256=est1mrN80vB_4-j-2yuAr_l_7rNzO4AJlqpq74zO5ow,682
11
+ src/djresttoolkit/middlewares/__init__.py,sha256=GZHU3Yy4xXoEi62tHn0UJNxN6XgGM2_HES8Bt5AS5Lk,100
12
+ src/djresttoolkit/middlewares/_response_time_middleware.py,sha256=1wCwdkW5Ng6HJo8zx0F7ylms84OGP-1K0kbyG6Vacuk,908
11
13
  src/djresttoolkit/migrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
14
  src/djresttoolkit/models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
- djresttoolkit-0.2.0.dist-info/METADATA,sha256=Xr6JLGRsN0NlwnQ_Nu0HcdBv6Sfs7RKeIdYOq4GVoL8,4374
14
- djresttoolkit-0.2.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
15
- djresttoolkit-0.2.0.dist-info/entry_points.txt,sha256=YMhfTF-7mYppO8QqqWnvR_hyMWvoYxD6XI94_ViFu3k,60
16
- djresttoolkit-0.2.0.dist-info/licenses/LICENSE,sha256=8-oZM3yuuTRjySMbVKX9YXYA7Y4M_KhQNBYXPFjeWUo,1074
17
- djresttoolkit-0.2.0.dist-info/RECORD,,
15
+ src/djresttoolkit/views/__init__.py,sha256=XrxBrs6sH4HmUzp41omcmy_y94pSaXAVn01ttQ022-4,76
16
+ src/djresttoolkit/views/_exceptions/__init__.py,sha256=DrCUxuPNyBR4WhzNutn5HDxLa--q51ykIxSG7_bFsOI,83
17
+ src/djresttoolkit/views/_exceptions/_exception_handler.py,sha256=lg6kfAABex-UbAsF78uX-M-ZnJ3u1vK1eIXytb-4KSw,2375
18
+ djresttoolkit-0.4.0.dist-info/METADATA,sha256=FGDP5PR0AZoaPvEyrG95DVC516vGOWlXk2ZgyLfm8kE,4374
19
+ djresttoolkit-0.4.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
20
+ djresttoolkit-0.4.0.dist-info/entry_points.txt,sha256=YMhfTF-7mYppO8QqqWnvR_hyMWvoYxD6XI94_ViFu3k,60
21
+ djresttoolkit-0.4.0.dist-info/licenses/LICENSE,sha256=8-oZM3yuuTRjySMbVKX9YXYA7Y4M_KhQNBYXPFjeWUo,1074
22
+ djresttoolkit-0.4.0.dist-info/RECORD,,
@@ -0,0 +1,3 @@
1
+ from ._response_time_middleware import ResponseTimeMiddleware
2
+
3
+ __all__ = ["ResponseTimeMiddleware"]
@@ -0,0 +1,32 @@
1
+ import logging
2
+ import time
3
+ from collections.abc import Callable
4
+
5
+ from django.http import HttpRequest, HttpResponse
6
+
7
+ # Get logger from logging.
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ class ResponseTimeMiddleware:
12
+ """Calculte response response time."""
13
+
14
+ def __init__(
15
+ self,
16
+ get_response: Callable[[HttpRequest], HttpResponse],
17
+ ) -> None:
18
+ "Initilize response time middleware."
19
+ self.get_response = get_response
20
+
21
+ def __call__(self, request: HttpRequest) -> HttpResponse:
22
+ """Handle to response response time calculation."""
23
+ start_time = time.perf_counter()
24
+ response = self.get_response(request)
25
+ end_time = time.perf_counter()
26
+
27
+ response_time = f"{round(end_time - start_time, 5)} seconds"
28
+ response["X-Response-Time"] = response_time
29
+
30
+ logger.info(f"Request processed in {response_time}")
31
+
32
+ return response
@@ -0,0 +1,3 @@
1
+ from ._exceptions import exception_handler
2
+
3
+ __all__ = ["exception_handler"]
@@ -0,0 +1,3 @@
1
+ from ._exception_handler import exception_handler
2
+
3
+ __all__ = ["exception_handler"]
@@ -0,0 +1,64 @@
1
+ from typing import Any, cast
2
+
3
+ from django.core.cache import cache
4
+ from django.utils import timezone
5
+ from rest_framework import status, views
6
+ from rest_framework.request import Request
7
+ from rest_framework.response import Response
8
+ from rest_framework.throttling import AnonRateThrottle
9
+
10
+
11
+ def exception_handler(exc: Exception, context: dict[str, Any]) -> Response | None:
12
+ """
13
+ Custom exception handler that preserves DRF's default functionality
14
+ while adding custom throttling behavior.
15
+ """
16
+
17
+ # Call DRF's default exception handler first
18
+ response: Response | None = views.exception_handler(exc, context)
19
+
20
+ request: Request | None = context.get("request")
21
+ view = context.get("view")
22
+
23
+ if request and view:
24
+ # Pick throttle classes from view or default to AnonRateThrottle
25
+ throttle_classes: list[type[AnonRateThrottle]] = getattr(
26
+ view, "throttle_classes", [AnonRateThrottle]
27
+ )
28
+
29
+ for throttle_class in throttle_classes:
30
+ throttle = throttle_class()
31
+ cache_key = throttle.get_cache_key(request, view)
32
+ if not cache_key:
33
+ continue
34
+
35
+ history: list[float] = cache.get(cache_key, [])
36
+ now = timezone.now().timestamp()
37
+ duration: float = cast(float, throttle.duration) # type: ignore[attr-defined]
38
+
39
+ # Keep only non-expired timestamps
40
+ history = [float(ts) for ts in history if now - float(ts) < duration]
41
+
42
+ # If throttle limit exceeded
43
+ if len(history) >= throttle.num_requests: # type: ignore[attr-defined]
44
+ retry_after: float = (
45
+ duration - (now - history[0]) if history else duration
46
+ )
47
+
48
+ return Response(
49
+ data={
50
+ "detail": "Too many requests. Please try again later.",
51
+ "retry_after": {
52
+ "time": round(retry_after, 2),
53
+ "unit": "seconds",
54
+ },
55
+ },
56
+ status=status.HTTP_429_TOO_MANY_REQUESTS,
57
+ )
58
+
59
+ # Otherwise add current timestamp
60
+ history.append(now)
61
+ cache.set(key=cache_key, value=history, timeout=duration)
62
+
63
+ # If DRF handled the exception, return that response
64
+ return response