Skip to main content

A collection of Django and DRF utilities to simplify API development.

Project description

🛠️ djresttoolkit (django rest toolkit)

PyPI version Python versions License

djresttoolkit is a collection of utilities and helpers for Django and Django REST Framework (DRF) that simplify common development tasks such as API handling, authentication, and email sending and much more.

✨ Features

  • Django REST Framework helpers (serializers, views, pagination, etc.)
  • Django utilities (e.g., email sending, model mixins)
  • Ready-to-use shortcuts to speed up API development
  • Lightweight, no unnecessary dependencies
  • Type Safe - written with modern Python type hints.

📦 Installation

  • By using uv:

    uv add djresttoolkit
    
  • By using pip:

    pip install djresttoolkit
    

📚 API Reference

1. EmailSender

from djresttoolkit.mail import EmailSender, EmailContent, EmailTemplate

EmailSender

Send templated emails.

Init

EmailSender(email_content: EmailContent | EmailContentDict)

Methods

send(to: list[str], exceptions: bool = False) -> bool
  • to: recipient emails
  • exceptions: raise on error if True, else logs error
  • Returns True if sent, False on failure

Example

content = EmailContent(
    subject="Hello",
    from_email="noreply@example.com",
    context={"username": "Alice"},
    template=EmailTemplate(
        text="emails/welcome.txt",
        html="emails/welcome.html"
    )
)
EmailSender(content).send(to=["user@example.com"])

EmailContent

  • subject, from_email, context, template (EmailTemplate)

EmailTemplate

  • text, html — template file paths

2. Custom DRF Exception Handler

from djresttoolkit.views import exception_handler

exception_handler(exc: Exception, context: dict[str, Any]) -> Response | None

A DRF exception handler that:

  • Preserves DRF’s default exception behavior.
  • Adds throttling support (defaults to AnonRateThrottle).
  • Returns 429 Too Many Requests with retry_after if throttle limit is exceeded.

Parameters

  • exc: Exception object.
  • context: DRF context dictionary containing "request" and "view".

Returns

  • Response — DRF Response object (with throttling info if applicable), or None.

Settings Configuration

In settings.py:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'djresttoolkit.views.exception_handler',
    # Other DRF settings...
}

Throttle Behavior

  • Uses view.throttle_classes if defined, else defaults to AnonRateThrottle.
  • Tracks requests in cache and calculates retry_after.
  • Cleans expired timestamps automatically.

3. Response Time Middleware

from djresttoolkit.middlewares import ResponseTimeMiddleware

ResponseTimeMiddleware

Middleware to calculate and log HTTP response time for each request.

Constructor from ResponseTimeMiddleware

ResponseTimeMiddleware(get_response: Callable[[HttpRequest], HttpResponse])
  • get_response: The next middleware or view callable.

Usage

Add it to your Django MIDDLEWARE in settings.py:

MIDDLEWARE = [
    # Other middlewares...
    'djresttoolkit.middlewares.ResponseTimeMiddleware',
]

Behavior

  • Measures the time taken to process each request.
  • Adds a header X-Response-Time to each HTTP response.
  • Logs the response time using Django's logging system.

The response headers will include

X-Response-Time: 0.01234 seconds

Logs a message

INFO: Request processed in 0.01234 seconds

4. Throttle Utilities

ThrottleInfoJSONRenderer

from djresttoolkit.renderers import ThrottleInfoJSONRenderer

A custom DRF JSON renderer that automatically attaches throttle information to response headers.

Usage (settings.py)

REST_FRAMEWORK = {
    "DEFAULT_RENDERER_CLASSES": [
        "djresttoolkit.renderers.ThrottleInfoJSONRenderer",
        "rest_framework.renderers.BrowsableAPIRenderer",
    ],
}

When enabled, every response includes throttle headers like:

X-Throttle-User-Limit: 100
X-Throttle-User-Remaining: 98
X-Throttle-User-Reset: 2025-08-18T07:30:00Z
X-Throttle-User-Retry-After: 0

ThrottleInspector

from djresttoolkit.throttling import ThrottleInspector

Utility class to inspect DRF throttle usage for a view or request.

Constructor for ThrottleInspector

ThrottleInspector(
    view: APIView,
    request: Request | None = None,
    throttle_classes: list[type[BaseThrottle]] | None = None,
)

Key Methods

  • get_details() -> dict[str, Any] Returns structured throttle info: limit, remaining, reset time, retry_after.

  • attach_headers(response: Response, throttle_info: dict | None) Attaches throttle data to HTTP headers.

🛠️ Planned Features

  • Add more utils

🤝 Contributing

Contributions are welcome! Please open an issue or PR for any improvements.

📜 License

MIT License — See LICENSE.

👤 Author

For questions or assistance, contact Shailesh at shaileshpandit141@gmail.com.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

djresttoolkit-0.6.1.tar.gz (12.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

djresttoolkit-0.6.1-py3-none-any.whl (23.1 kB view details)

Uploaded Python 3

File details

Details for the file djresttoolkit-0.6.1.tar.gz.

File metadata

  • Download URL: djresttoolkit-0.6.1.tar.gz
  • Upload date:
  • Size: 12.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.6

File hashes

Hashes for djresttoolkit-0.6.1.tar.gz
Algorithm Hash digest
SHA256 89096f4cdf251b7513cf1440fa8ed7efa1acefa1051e1423a7fdc8a59978670f
MD5 7336c76b8237ebe2733df24548c5bc11
BLAKE2b-256 35b51962a7fcdb5b4b900874dc9ca2f3271e8d7b7175c3535d472d129f1e2bc2

See more details on using hashes here.

File details

Details for the file djresttoolkit-0.6.1-py3-none-any.whl.

File metadata

File hashes

Hashes for djresttoolkit-0.6.1-py3-none-any.whl
Algorithm Hash digest
SHA256 d47629e59d9ddb833fe03c6a2c7270bef07c9ae38bb939df200dc76cf48fb74e
MD5 7d53b0cf55855b4c06727afaad67747a
BLAKE2b-256 5c91ffd5e63524c4e15fc8e11f204b35a21d99d3e73398c8834bd9a44d25214c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page