Skip to main content

A flexible Django REST Framework permission class with Redis caching support

Project description

drf-perm-control

A flexible Django REST Framework permission class with caching support.

PyPI version Python Versions Django Versions License: MIT

Features

  • 🔐 Django Permission Integration - Uses Django's built-in permission system
  • Caching Support - Built-in permission caching for better performance
  • 🎯 Simple Configuration - Just set perm_control on your views
  • 🔧 Highly Customizable - Extend and customize to fit your needs
  • 📦 Zero Dependencies - Only requires Django and DRF (Redis optional)

Installation

pip install drf-perm-control

With Redis caching support:

pip install drf-perm-control[redis]

Quick Start

from rest_framework.views import APIView
from rest_framework.response import Response
from drf_perm_control import ApiPermission


class MyView(APIView):
    permission_classes = [ApiPermission]
    perm_control = "myapp.mymodel"  # Maps to Django permissions

    def get(self, request):
        # Requires 'myapp.view_mymodel' permission
        return Response({"message": "Hello, World!"})

    def post(self, request):
        # Requires 'myapp.add_mymodel' permission
        return Response({"message": "Created!"})

Permission Mapping

The perm_control attribute maps HTTP methods to Django permissions:

HTTP Method Django Permission
GET {app}.view_{model}
POST {app}.add_{model}
PUT {app}.change_{model}
PATCH {app}.change_{model}
DELETE {app}.delete_{model}

Customization

Custom Permission Class

from drf_perm_control import ApiPermission


class CustomApiPermission(ApiPermission):
    # Cache timeout in seconds (default: 300)
    cache_timeout = 600  # 10 minutes
    
    # Cache key prefix (default: "user_perms")
    cache_key_prefix = "my_app_perms"
    
    # User types that bypass permission checks
    admin_user_types = ["ADMIN", "DEV"]

Custom Permission Mapping

from drf_perm_control import ApiPermission


class CustomApiPermission(ApiPermission):
    permission_map = {
        "GET": "{app_label}.view_{model_name}",
        "POST": "{app_label}.add_{model_name}",
        "PUT": "{app_label}.change_{model_name}",
        "PATCH": "{app_label}.change_{model_name}",
        "DELETE": "{app_label}.delete_{model_name}",
        "OPTIONS": "{app_label}.view_{model_name}",  # Add OPTIONS support
    }

Using the Mixin

You can also use PermControlMixin to build your own permission classes:

from rest_framework.permissions import BasePermission
from drf_perm_control import PermControlMixin


class MyCustomPermission(PermControlMixin, BasePermission):
    def has_permission(self, request, view):
        # Your custom logic here
        perm = self.get_permission_string(request.method, view.perm_control)
        return self.check_permission(request.user, perm)

Configuration

Django Settings

No additional Django settings are required. The package uses Django's built-in cache framework.

For Redis caching, configure Django's cache backend:

# settings.py
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

API Reference

ApiPermission

Main permission class for DRF views.

Attributes:

  • permission_map - Dict mapping HTTP methods to permission string templates
  • cache_timeout - Cache timeout in seconds (default: 300)
  • cache_key_prefix - Prefix for cache keys (default: "user_perms")
  • admin_user_types - List of user types that bypass permission checks

Methods:

  • has_permission(request, view) - Check view-level permission
  • has_object_permission(request, view, obj) - Check object-level permission

PermControlMixin

Mixin providing permission control utilities.

Methods:

  • get_cache_key(user_id) - Generate cache key for user permissions
  • get_permission_string(method, perm_control) - Get required permission string
  • get_cached_permissions(user) - Get user permissions from cache or database
  • check_permission(user, perm) - Check if user has the specified permission
  • is_admin_user(user) - Check if user is an admin-level user

Contributing

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

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development

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

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run tests with coverage
pytest --cov=drf_perm_control

# Format code
black src tests
ruff check src tests --fix

License

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog

See CHANGELOG.md for a list of changes.

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_perm_control-0.1.0.tar.gz (7.2 kB view details)

Uploaded Source

Built Distribution

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

drf_perm_control-0.1.0-py3-none-any.whl (6.2 kB view details)

Uploaded Python 3

File details

Details for the file drf_perm_control-0.1.0.tar.gz.

File metadata

  • Download URL: drf_perm_control-0.1.0.tar.gz
  • Upload date:
  • Size: 7.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.6

File hashes

Hashes for drf_perm_control-0.1.0.tar.gz
Algorithm Hash digest
SHA256 2964a04e1170ff8ff15cb8c3a7c58f5ef48f17621fc7fd47babaa696f08c7cb9
MD5 e856573b58197fe8a5514dd09f63e7d8
BLAKE2b-256 a7989718e815acd364731e18ed2e1b88503fa56d86ce92b6588173877019e140

See more details on using hashes here.

File details

Details for the file drf_perm_control-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for drf_perm_control-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8e0eb953fcdf19e5f848de3d57b36faa9187042466f86db5ee23a2b85d1d325f
MD5 6a3b9fbd0fced02e6dded60f412cc0fd
BLAKE2b-256 f471fbe11401664ebe19bf64d192d9f6d8f561fd427cdf597e7b3b7cda4d33f8

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