Install & Compatibility
Where this runs
tested against v3.5 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 0.000s · 17.9MB
glibcpy 3.10–3.920 runs
installs and imports cleanly · install 1.5s · import 0.000s · 18MB
16MB installed
● package 16MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
Predicate
✓ from rules import Predicate
✗ from rules import rule
RuleSet
✓ from rules import RuleSet
add_perm
✓ from rules import add_perm
This quickstart demonstrates defining a simple permission predicate, adding it as a named rule, and using the `PermissionsRequiredMixin` in a Django class-based view. It also shows how to manually test a rule.
import rules
from rules import Predicate
from django.conf import settings
from django.apps import apps
from django.http import HttpResponse
from django.views.generic import View
settings.configure(
INSTALLED_APPS=['django.contrib.auth', 'django.contrib.contenttypes', 'rules'],
SECRET_KEY='a-very-secret-key',
TEMPLATES=[{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': {'string_if_invalid': 'INVALID'}}],
DEBUG=True
)
apps.populate(settings.INSTALLED_APPS)
# 1. Define a simple predicate
is_staff = Predicate(lambda u: u.is_staff)
# 2. Add the rule with a name
rules.add_rule('can_access_staff_area', is_staff)
# 3. Use it in a Django View
from rules.contrib.views import PermissionsRequiredMixin
from django.contrib.auth.models import User
class StaffAreaView(PermissionsRequiredMixin, View):
permission_required = 'can_access_staff_area'
def get(self, request):
return HttpResponse("Welcome, staff member!")
# Example of creating a mock user and checking permission (for demonstration)
mock_user_staff = User(username='staffuser', is_staff=True)
mock_user_non_staff = User(username='regularuser', is_staff=False)
# This would typically happen inside a request context
can_access_staff_true = rules.test_rule('can_access_staff_area', mock_user_staff)
can_access_staff_false = rules.test_rule('can_access_staff_area', mock_user_non_staff)
assert can_access_staff_true is True
assert can_access_staff_false is False
print(f"Staff user can access staff area: {can_access_staff_true}")
print(f"Regular user can access staff area: {can_access_staff_false}")
Upgrade
Version history
3.5latest on PyPI · released Sep 2, 2024
Audit
Dependencies
DjangorequiredCore framework rules integrates with.