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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for django_model_hooks-1.0.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | a0c72a1433ab9c9a1d1335c2831a54dc39fface873baa45392d0a3325451b66c |
|
MD5 | 29d0b0e2530e2b24dbd340496bcbcd87 |
|
BLAKE2b-256 | 2bb40950fe3d5b47be093d0f4530417c134907cf0d367c2cf3b3dd640041c05b |