Package: sitech-notifier
sitech-notifierOfficial supported notification library for real-time, sms and email with notifications center.RequirementsPython (3.6, 3.7, 3.8)Django (2.0, 2.1, 2.2, 3.0)CeleryInstallationInstall withpip:pip install sitech-notifierIf you want to enable real time notifications:pip install sitech-notifier[realtime]Modify yoursettings.py:INSTALLED_APPS=[...,'sitech_notifier',]Runpython manage.py migrateBasic UsageSetupFirst, you have to set up delivery backends in yoursettings.py, for example:SITECH_NOTIFIER_DELIVERY_BACKENDS=['sitech_notifier.delivery.backends.EmailDeliveryBackends',# default'sitech_notifier.delivery.backends.PusherBackend','your_app.backends.CustomDeliveryBackend']For list of built-in delivery backends, go toDelivery backendsCustom delivery backendOften you'll need custom delivery backend, for example for SMS notifications, or if you
want allow users to disable some delivery backends.To create custom delivery backend, you can subclassNotificationDeliveryBackend.
Overridingperform_sendis required,notification_enabledis optional.Example:classConcreteSMSBackend(BaseSMSDeliveryBackend):defnotification_enabled(self,notification):returnnotification.user.profile.sms_notifications_enableddefperform_send(self,notification):mobile_number=notification.user.profile.mobile_numberrequests.post(SMS_GATEWAY_URL,{'api_key':SMS_GATEWAY_API_KEY,'mobile_number':mobile_number,'message':notification.full_body_text})Defining notificationsSuppose you want to create a notification  on a new comment on your blog post. First,
you have to define a subclass ofBaseNotification:fromsitech_notifier.coreimportBaseNotificationclassBlogPostCommentNotification(BaseNotification):template_name='notifications/blog_post_comment.html'description='New comment on a blog post'notification_type='blog_post_comment'Check all notification customization options innotification factoriesThen, create fileyour_app/templates/notifications/blog_post_comment.htmlwith
such content:{% block subject %}New comment on a post blog{% endblock subject %}
{% block short_body %}
    There is a new comment on your blog post "{{ post.title }}".
{% endblock short_body %}
{% block text_body %}
    Hello, there is a new comment on your blog post "{{ post.title }}".
{% endblock text_body %}
{% block html_body %}<h4>Hello,</h4><p>There is a new comment on your blog post "{{ post.title }}".</p>{% endblock html_body %}Then you have to define an event which will fire the notification, seeeventsfor the details.Enabling Pusher notificationsYou can also want to enable real-time notifications which would appear in application.At first, you have to set up Pusher application (visithttps://pusher.com)Then you have to addPusherDeliveryBackendtoSITECH_NOTIFIER_DELIVERY_BACKENDSand configure your app settingsSITECH_NOTIFIER_DELIVERY_BACKENDS=[...,'sitech_notifier.delivery.backends.PusherDeliveryBackends',]PUSHER_APP_ID='app_id'PUSHER_KEY='pusher_key'PUSHER_SECRET='secret'PUSHER_CLUSTER='if-other-than-default-us-east-1'Then you have to edit your base template, for exampleindex.html:{% load sitech_notifier %}
...<script>constNOTIFICATION_CALLBACK=data=>{alert(data.message)};</script>{% enable_pusher_notifications %}NOTIFICATION_CALLBACKis JS function which is being called when notification
comes to the user's private channel. Here we used standard JSalert, but in practice
you will want to use more advanced JS notification liketoastr:toastr.info(data.message,"",{onclick:function(){window.location=data.link;}});DocumentationModelsAbstractNotificationSource:sitech_notifier.models.AbstractNotificationBase model for notifications, subclass
this if you need any custom fields and extra data.Fields:user-settings.AUTH_USER_MODELforeign key, recipient of the notificationsubject- notification subject, used for email notificationsshort_body- short message of the notification, can be used for real-time in-app
notifications or inbox pagefull_body_txt-(optional)long notification body in plain text. Mainly used for email
notificationsfull_body_html-(optional)long notification body in HTML. Mainly used for email
notificationslink-(optional)URL to the resource related to the notification.Example use: Notification on new blog post, include blog post URL in the notificationis_new- Boolean indicating if notification is new.Trueby default.NotificationSource:sitech_notifier.models.NotificationSubclass ofAbstractNotificationwithcreated_at,modified_atfields and default
ordering(-created_at,). Use this model if you don't need any custom data.Custom notificationsIf you want to create custom notification model, subclassAbstractNotificationand add tosettings.py:SITECH_NOTIFIER_NOTIFICATION_MODEL='your_app.CustomNotification'Notification factoriesNotification factories are subclasses ofsitech_notifier.notifications.BaseNotificationclass. They are used to define specific notification in the application. Calling such
subclass creates a notification with all needed data and sends it with Celery
via configured delivery backends.Notification signature:SpecificNotification(user, event)userandeventare saved as attributes and accessible throughself.Eventis an instance ofEventmodel.Notifications should not be called manually, process of sending the notifications
is handled by events.
Notifications are sent by emitting an event which registered the notification as callback. SeeEventsfor the details.Notification has to override following attributes:template_name- path to the template, seenotification templatesdescription- description what causes the notification, for example:
"New comment on a blog post"get_context_from_event(event)(static method) - get context fromEventobject.If notification does not override these attributes and methods, it will be treated as abstract,
and therefore not be registered innotification_typesOptional attributes:notification_type- notification type code, for example:new_blog_post. Notification
type has to be unique, if not defined, it will evaluate to lowercased class name. If
notification of such type already exists,DuplicateNotificationTypewill be raised.Methods (all optional):get_notification_link(self)-  get URL linked to the notification, for example:return kwargs['blog_post'].get_absolute_url()get_notification_language(self)- get language in which notification should be
rendered, for example:return self.user.profile.language. Defaults tosettings.LANGUAGE_CODEtransform_html_body(self, html_body)- transform HTML body before sending,
override this if you want for example add CSS to your emails with library such aspremailerHelper functions:sitech_notifier.notifications.get_notification_types()- get all registered
notificationssitech_notifier.notifications.get_notification_description(notification_type)- get
description of a notification with given typeNotification templateNotification template has to look like this, blockssubjectandshort_bodyare required.{% block subject %}{% endblock %}
{% block short_body %}{% endblock %}
{% block text_body %}{% endblock %}
{% block html_body %}{% endblock %}Delivery backendsDelivery backends are subclasses ofNotificationDeliveryBackendabstract class with
overridden methodperform_send.Email backendSource:sitech_notifier.delivery.backends.EmailDeliveryBackendSends notification to the user via email,DEFAULT_FROM_EMAILsetting is required.SMS backendSource:sitech_notifier.delivery.backends.BaseSMSDeliveryBackendThis backend does NOT work out of the box. It needs to be subclassed andperform_sendmethod must be provided.ExamplePusher delivery backendSource:sitech_notifier.delivery.backends.PusherDeliveryBackendSends notification to the user's Pusher private channel, making it possible to enable
real time in-app notifications.Library also suppliesenable_pusher_notificationstemplatetag which should be included
in the base template. Before using the templatetag, JS functionNOTIFICATION_CALLBACKhas to be defined.Required settings:PUSHER_APP_IDPUSHER_KEYPUSHER_SECRETOptional settings:PUSHER_CLUSTER- if other than defaultus-east-1PUSHER_OPTIONS- otherkwargsforPusherinstancePusher docs:https://pusher.com/docs/channelsEventssitech-notifierpackage also ships with events library, which can be used to simplify
the process of sending notifications.Basic UsageEventsCreateevents.pyfile in your app and define events:To connect notification to the events, useregister_notificationdecorator. Decorated function
should return aUseror iterable of users.fromsitech_notifier.coreimportBaseEventclassNewBlogPost(BaseEvent):name='new-blog-post'@register_notification(NewBlogPostNotification)defnotify_new_blog_post(self):post=self.targetreturnpost.blog.followers@register_notification(PostSubmittedNoification)defnotify_post_submitted(self):post=self.targetreturnpost.authorNote that your notification has to overrideget_context_from_eventstatic method.Example:classNewBlogPostNotification(BaseNotification):...@staticmethoddefget_context_from_event(event):return{'post':event.target}Now, every timeNewBlogPostis emitted, a notification is sent to all blogfollowers,
withpost=postas a keyword argument.Emitting eventsEvents can be emitted with two arguments:target(required) - djangoModelinstance which is the target of the self, for example
when there is a new post on a blog, blog is the targetactor(optional) - djangoUser(built-in or custom) instance who fired the
notification. Following the example, post author could be the actor, but it's
possible to retrieve him directly from the target, so it can be skipped.Events are emitted with following call:Event(target,actor=None).emit()Side effectsEvents can also handle actions which are not related to the notifications. For this purpose,
overrideside_effectsstatic method of Event's classclassCustomEvent(BaseEvent):@staticmethoddefside_effects(self):some_side_effect(self)