Skip to main content

Django REST Framework Common Utilities - Modular apps for enhanced DRF functionality

Project description

DRF Commons

⚠️ UNDER DEVELOPMENT: This library is currently under active development. APIs may change, and some features may not be fully stable yet.

A comprehensive collection of reusable Django REST Framework utilities and components designed to accelerate API development.

Features

Core Modules

  • Current User: Middleware and utilities for accessing the current user context
  • Debug: Advanced logging and debugging tools with categorized loggers
  • Decorators: Performance monitoring, caching, database optimization, and logging decorators
  • Filters: Enhanced filtering and ordering capabilities including computed fields
  • Middlewares: Current user tracking and debug middleware
  • Models: Base models, mixins, and custom fields for common patterns
  • Pagination: Flexible pagination classes
  • Response: Standardized API response utilities
  • Serializers: Enhanced serializers with custom fields and mixins
  • Views: ViewSet mixins for CRUD, bulk operations, and import/export

Services

  • Export File: Export data to CSV, XLSX, and PDF formats
  • Import from File: Robust file import with validation and bulk operations

Installation

Install the base package:

pip install drf-commons

Install with specific features:

# For export functionality (XLSX and PDF)
pip install drf-commons[export]

# For import functionality
pip install drf-commons[import]

# For dynamic configuration
pip install drf-commons[config]

# For all features
pip install drf-commons[all]

# For development
pip install drf-commons[dev,test]

Quick Start

1. Add to INSTALLED_APPS

INSTALLED_APPS = [
    # ... your apps
    'drf_commons.current_user',
    'drf_commons.debug',
    'drf_commons.filters',
    'drf_commons.pagination',
    'drf_commons.response',
    'drf_commons.serializers',
    'drf_commons.views',
]

2. Add Middleware (Optional)

MIDDLEWARE = [
    # ... other middleware
    'drf_commons.middlewares.current_user.CurrentUserMiddleware',
    'drf_commons.middlewares.debug.DebugMiddleware',
]

3. Use in Your Code

from drf_commons.views.base import BaseViewSet
from drf_commons.serializers.base import BaseSerializer
from drf_commons.models.base import BaseModel
from drf_commons.pagination.base import CustomPageNumberPagination

class MyModel(BaseModel):
    # Your model fields
    pass

class MySerializer(BaseSerializer):
    class Meta:
        model = MyModel
        fields = '__all__'

class MyViewSet(BaseViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MySerializer
    pagination_class = CustomPageNumberPagination

Usage Examples

Export Data

from drf_commons.services import ExportService

service = ExportService()

# Export to CSV (no optional dependencies required)
response = service.export_csv(
    data_rows=data,
    includes=['id', 'name', 'created_at'],
    column_config={},
    filename='export.csv',
    export_headers=[],
    document_titles=[]
)

# Export to XLSX (requires openpyxl)
response = service.export_xlsx(...)

# Export to PDF (requires weasyprint)
response = service.export_pdf(...)

Import Data

from drf_commons.services import FileImportService

config = {
    'model': MyModel,
    'fields': {
        'name': {'required': True},
        'email': {'required': True, 'unique': True},
    }
}

service = FileImportService(config)
result = service.import_file(file_path)

Use Decorators

from drf_commons.decorators.performance import measure_performance
from drf_commons.decorators.cache import cached_method

class MyViewSet(BaseViewSet):
    @measure_performance
    @cached_method(timeout=300)
    def expensive_operation(self):
        # Your expensive operation
        pass

Requirements

  • Python >= 3.8
  • Django >= 3.2
  • djangorestframework >= 3.12

Optional Dependencies

Different features require different dependencies:

Core Package (No optional dependencies)

The base installation includes:

  • Models, Serializers, Views, Pagination, Response utilities
  • CSV export (no additional dependencies required)
  • Filters, Decorators, Middleware

File Export ([export])

For XLSX and PDF export functionality:

  • openpyxl >= 3.0 - Excel (XLSX) export
  • weasyprint >= 60.0 - PDF export

File Import ([import])

For importing data from CSV and Excel files:

  • pandas >= 1.3 - Data processing and file parsing
  • openpyxl >= 3.0 - Excel file reading

Dynamic Configuration ([config])

For runtime configuration management:

  • django-constance >= 2.9 - Dynamic Django settings

Development

Setup Development Environment

# Clone the repository
git clone https://github.com/yourusername/drf-common.git
cd drf-common

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install in development mode with all dependencies
pip install -e .[dev,test,all]

Run Tests

pytest

Code Quality

# Format code
black .

# Sort imports
isort .

# Lint
flake8

# Type checking
mypy drf_commons

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License.

Author

Victoire HABAMUNGU

Support

For issues and questions, please use the GitHub issue tracker.

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

drf_commons-1.0.1.tar.gz (129.7 kB view details)

Uploaded Source

Built Distribution

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

drf_commons-1.0.1-py3-none-any.whl (189.1 kB view details)

Uploaded Python 3

File details

Details for the file drf_commons-1.0.1.tar.gz.

File metadata

  • Download URL: drf_commons-1.0.1.tar.gz
  • Upload date:
  • Size: 129.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.13

File hashes

Hashes for drf_commons-1.0.1.tar.gz
Algorithm Hash digest
SHA256 9fcb2de6a53152ab9b9e810b668ac686fde55f00b187c141d09abe3fbbd97875
MD5 2dbfa5667c7768a8c02c009d1e40b62b
BLAKE2b-256 f2c4d5fbc5de27e55e9e78e409e0a2582047c2b47754239fc1a25a7bd561836d

See more details on using hashes here.

File details

Details for the file drf_commons-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: drf_commons-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 189.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.13

File hashes

Hashes for drf_commons-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 bd8a99841aaa4a9c501303863fb72c649c1b4570c94898e585656d6f99777dbb
MD5 59a05b67f06da524f8101b0523520544
BLAKE2b-256 ad12cd66f02a39ca979a788d60c56c40d8deaaf8a737e651a0e8a9b1d5c3660a

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