Skip to main content

Model hooks for Django

Project description

django-model-hooks

Model hooks for Django.

Rationale

Add persistent receivers with logging for django model signals.

Support

Supports: Python 3.10.

Supports Django Versions: 4.2.7

Installation

$ pip install django-model-hooks

Usage

Add model_hooks to INSTALLED_APPS.

Run migrations:

python manage.py migrate

Add a module model_hooks_registry to one or more of your apps. Decorate any function you want to be triggered by a hook with the model_hook decorator.

Post serialized data to a rest endpoint on creation of a myapp.MyModel instance:

# model_hooks_registry.py
import json

import requests
from model_hooks.decorators import model_hook
from model_hooks.events import create_event

from myapp.models import MyModel
from myapp.serializers import serializer


@model_hook(MyModel, create_event, serializer=serializer)
def hook_create(instance, payload, **kwargs):
    requests.post(kwargs.get('rest_url'), data=json.dumps(payload))

Or specify a special tag for the triggering of the function call:

# model_hooks_registry.py
import json

import requests
from model_hooks.decorators import model_hook
from model_hooks.events import create_event

from myapp.models import MyModel
from myapp.serializers import serializer


@model_hook(MyModel, create_event, serializer=serializer, tag='rest')
def hook_create(instance, payload, **kwargs):
    requests.post(kwargs.get('rest_url'), data=json.dumps(payload))

You may also define a custom event:

# model_hooks_registry.py
import json

import requests
from model_hooks.decorators import model_hook
from model_hooks.events import HookEvent

from myapp.models import MyModel
from myapp.serializers import serializer


custom_event = HookEvent('custom_event')


@model_hook(MyModel, custom_event, serializer=serializer)
def hook_custom(instance, payload, **kwargs):
    requests.post(kwargs.get('rest_url'), data=json.dumps(payload))

Trigger the event:

from model_hooks.signals import hook_event

from myapp.model_hooks_registry import custom_event
from myapp.models import MyModel

instance = MyModel.objects.get(pk=1)
hook_event.send(MyModel, model=MyModel, instance=instance, event=custom_event)

Now go to the Django admin and add the hooks for the appropriate models and events.

Prune the log table:

python manage.py log_prune

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

django-model-hooks-1.0.1.tar.gz (6.2 kB view hashes)

Uploaded Source

Built Distribution

django_model_hooks-1.0.1-py3-none-any.whl (8.9 kB view hashes)

Uploaded Python 3

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