Skip to main content

A Triggers system for Django made for implementing event-based business logic configurable through the Django admin site.

Project description

django-triggers Latest Version

Test Status codecov Python Support

django-triggers is intended for implementing event-based business logic configurable through the Django admin site.

Install

pip install dj-triggers
INSTALLED_APPS = [
    ...
    "polymorphic",
    "triggers",
    ...
]

Prerequisites

Celery is required to be setup in your project.

Quickstart

Let's consider a simple tasks app with a model Task and we want to email a user when a task is completed.

  1. Add event, action and condition models into your app's models.py

By doing this, we separate the development of the trigger components from their configuration within the Django admin panel. This ensures a more modular and manageable approach to building and configuring triggers.

The full code example is available in tests directory.

from django.dispatch import receiver, Signal
from django.contrib.auth.models import User
from django.db import models, transaction

from triggers.models import Action,  Event


# Our domain model
class Task(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=128)
    is_completed = models.BooleanField(default=False, db_index=True, editable=False)
    is_important = models.BooleanField(default=False)

    completed = Signal()

    def complete(self):
        if not self.is_completed:
            self.is_completed = True
            self.save()
            transaction.on_commit(lambda: self.completed.send(sender=self.__class__, task=self))


# At first, implement an Event which will trigger the notification.
class TaskCompletedEvent(Event):
    # By setting the following `important_only` field through the Django admin site 
    # we can configure what tasks (all or important only) we want to notify the users about.
    important_only = models.BooleanField(
        default=False, 
        help_text='Fire the event for important tasks only if checked.',
    ) 

    def should_be_fired(self, **kwargs) -> bool:
        if self.important_only:
            return Task.objects.filter(id=kwargs['task_id'], is_important=True).exists()
        return True


# Then we need to fire `TaskCompletedEvent` when a task is marked as completed.
@receiver(Task.completed)
def on_task_completed(sender, task: Task, **kwargs):
    for event in TaskCompletedEvent.objects.all():
        transaction.on_commit(lambda: event.fire_single(task.user_id, task_id=task.id))


# At the end, create an Action implementing email notification.
class SendEmailAction(Action):
    subject = models.CharField(max_length=256)
    message = models.TextField()

    def perform(self, user: User, context: Dict[str, Any]):
        user.email_user(self.subject, self.message)
  1. Makemigrations and migrate
python manage.py makemigrations
python manage.py migrate
  1. Add trigger on the Django admin site

Don't forget to enable it :)

SCR-20230315-sooo
  1. Use the trigger!
task = Task.objects.get(id=...)  # Get your task
task.complete()  # And mark it as completed

You may also trigger it manually from the Django admin site if you're checking the test app example.

image

Development

Run a django-admin command, e.g. makemigrations

poetry run python -m django makemigrations --settings=tests.app.settings

Run isort

poetry run isort triggers tests

Run flake8

poetry run flake8 triggers tests

Run mypy

poetry run mypy triggers tests

Run pytest

poetry run pytest

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

dj_triggers-1.0.1.tar.gz (10.2 kB view details)

Uploaded Source

Built Distribution

dj_triggers-1.0.1-py3-none-any.whl (11.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: dj_triggers-1.0.1.tar.gz
  • Upload date:
  • Size: 10.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.4.0 CPython/3.11.2 Darwin/21.6.0

File hashes

Hashes for dj_triggers-1.0.1.tar.gz
Algorithm Hash digest
SHA256 8263c3e6c1d9a8e3cce4052325e4e5e22f9211d1ebb8c24f367295b2c5834f1b
MD5 fe107c405230ab250a7d23dda3daa490
BLAKE2b-256 8503127beb3bde4355218251d4ed4b09a8d75b22f420c31679e7f9f29bf13b61

See more details on using hashes here.

File details

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

File metadata

  • Download URL: dj_triggers-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 11.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.4.0 CPython/3.11.2 Darwin/21.6.0

File hashes

Hashes for dj_triggers-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 2e8c24d9bef43209c8a04518f122e35aa9f70382e7da217ebff78927387e1ea9
MD5 bd5f6fcad29083e3f7e9c8ca7b1bca92
BLAKE2b-256 1cb80f15c1e4e5fceefc254c68be9f02640ac0098051d73035097d36acd8d59a

See more details on using hashes here.

Supported by

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