Package: django-push-notifications
A minimal Django app that implements Device models that can send messages through APNS, FCM/GCM, WNS and WebPush.The app implements four models:GCMDevice,APNSDevice,WNSDeviceandWebPushDevice. Those models share the same attributes:name(optional): A name for the device.active(default True): A boolean that determines whether the device will be sent notifications.user(optional): A foreign key to auth.User, if you wish to link the device to a specific user.device_id(optional): A UUID for the device obtained from Android/iOS/Windows APIs, if you wish to uniquely identify it.registration_id(required): The FCM/GCM registration id or the APNS token for the device.The app also implements an admin panel, through which you can test single and bulk notifications. Select one or more
FCM/GCM, APNS, WNS or WebPush devices and in the action dropdown, select “Send test message” or “Send test message in bulk”, accordingly.
Note that sending a non-bulk test message to more than one device will just iterate over the devices and send multiple
single messages.
UPDATE_ON_DUPLICATE_REG_ID: Transform create of an existing Device (based on registration id) into a update. See below Update of device with duplicate registration ID for more details.DependenciesPython 3.6+Django 2.2+For the API module, Django REST Framework 3.7+ is required.For WebPush (WP), pywebpush 1.3.0+ is required (optional). py-vapid 1.3.0+ is required for generating the WebPush private key; however this
step does not need to occur on the application server.For Apple Push (APNS), apns2 0.3+ is required (optional).SetupYou can install the library directly from pypi using pip:$pipinstalldjango-push-notifications[WP,APNS]Edit your settings.py file:INSTALLED_APPS=(..."push_notifications")PUSH_NOTIFICATIONS_SETTINGS={"FCM_API_KEY":"[your api key]","GCM_API_KEY":"[your api key]","APNS_CERTIFICATE":"/path/to/your/certificate.pem","APNS_TOPIC":"com.example.push_test","WNS_PACKAGE_SECURITY_ID":"[your package security id, e.g: 'ms-app://e-3-4-6234...']","WNS_SECRET_KEY":"[your app secret key, e.g.: 'KDiejnLKDUWodsjmewuSZkk']","WP_PRIVATE_KEY":"/path/to/your/private.pem","WP_CLAIMS":{'sub':"mailto:development@example.com"}}NoteIf you need to support multiple mobile applications from a single Django application, seeMultiple Application Supportfor details.NoteIf you are planning on running your project withAPNS_USE_SANDBOX=True, then make sure you have set thedevelopmentcertificate as yourAPNS_CERTIFICATE. Otherwise the app will not be able to connect to the correct host. Seesettingsfor details.For more information about how to generate certificates, seedocs/APNS.You can learn more about APNS certificateshere.Native Django migrations are in use.manage.py migratewill install and migrate all models.Settings listAll settings are contained in aPUSH_NOTIFICATIONS_SETTINGSdict.In order to use FCM/GCM, you are required to includeFCM_API_KEYorGCM_API_KEY.
For APNS, you are required to includeAPNS_CERTIFICATE.
For WNS, you need both theWNS_PACKAGE_SECURITY_KEYand theWNS_SECRET_KEY.General settingsUSER_MODEL: Your user model of choice. Eg.myapp.User. Defaults tosettings.AUTH_USER_MODEL.UPDATE_ON_DUPLICATE_REG_ID: Transform create of an existing Device (based on registration id) into a update. See belowUpdate of device with duplicate registration IDfor more details.UNIQUE_REG_ID: Forces theregistration_idfield on all device models to be unique.APNS settingsAPNS_CERTIFICATE: Absolute path to your APNS certificate file. Certificates with passphrases are not supported. If iOS application was build with “Release” flag, you need to use production certificate, otherwise debug. Read more aboutGeneration of an APNS PEM file.APNS_AUTH_KEY_PATH: Absolute path to your APNS signing key file forToken-Based Authentication. Use this instead ofAPNS_CERTIFICATEif you are using.p8signing key certificate.APNS_AUTH_KEY_ID: The 10-character Key ID you obtained from your Apple developer accountAPNS_TEAM_ID: 10-character Team ID you use for developing your company’s apps for iOS.APNS_TOPIC: The topic of the remote notification, which is typically the bundle ID for your app. If you omit this header and your APNs certificate does not specify multiple topics, the APNs server uses the certificate’s Subject as the default topic.APNS_USE_ALTERNATIVE_PORT: Use port 2197 for APNS, instead of default port 443.APNS_USE_SANDBOX: Use ‘api.development.push.apple.com’, instead of default host ‘api.push.apple.com’. Default value depends onDEBUGsetting of your environment: ifDEBUGis True and you use production certificate, you should explicitly setAPNS_USE_SANDBOXto False.FCM/GCM settingsFCM_API_KEY: Your API key for Firebase Cloud Messaging.FCM_POST_URL: The full url that FCM notifications will be POSTed to. Defaults tohttps://fcm.googleapis.com/fcm/send.FCM_MAX_RECIPIENTS: The maximum amount of recipients that can be contained per bulk message. If theregistration_idslist is larger than that number, multiple bulk messages will be sent. Defaults to 1000 (the maximum amount supported by FCM).FCM_ERROR_TIMEOUT: The timeout on FCM POSTs.GCM_API_KEY,GCM_POST_URL,GCM_MAX_RECIPIENTS,GCM_ERROR_TIMEOUT: Same parameters for GCMWNS settingsWNS_PACKAGE_SECURITY_KEY: TODOWNS_SECRET_KEY: TODOWP settingsWP_PRIVATE_KEY: Absolute path to your private certificate file: os.path.join(BASE_DIR, “private_key.pem”)WP_CLAIMS: Dictionary with default value for the sub, (subject), sent to the webpush service, This would be used by the service if they needed to reach out to you (the sender). Could be a url or mailto e.g. {‘sub’: “mailto:development@example.com”}.WP_ERROR_TIMEOUT: The timeout on WebPush POSTs. (Optional)For more information about how to configure WebPush, seedocs/WebPush.Sending messagesFCM/GCM and APNS services have slightly different semantics. The app tries to offer a common interface for both when using the models.frompush_notifications.modelsimportAPNSDevice,GCMDevicedevice=GCMDevice.objects.get(registration_id=gcm_reg_id)# The first argument will be sent as "message" to the intent extras Bundle# Retrieve it with intent.getExtras().getString("message")device.send_message("You've got mail")# If you want to customize, send an extra dict and a None message.# the extras dict will be mapped into the intent extras Bundle.# For dicts where all values are keys this will be sent as url parameters,# but for more complex nested collections the extras dict will be sent via# the bulk message api.device.send_message(None,extra={"foo":"bar"})device=APNSDevice.objects.get(registration_id=apns_token)device.send_message("You've got mail")# Alert message may only be sent as text.device.send_message(None,badge=5)# No alerts but with badge.device.send_message(None,content_available=1,extra={"foo":"bar"})# Silent message with custom data.# alert with title and body.device.send_message(message={"title":"Game Request","body":"Bob wants to play poker"},extra={"foo":"bar"})device.send_message("Hello again",thread_id="123",extra={"foo":"bar"})# set thread-id to allow iOS to merge notificationsNoteAPNS does not support sending payloads that exceed 2048 bytes (increased from 256 in 2014).
The message is only one part of the payload, if
once constructed the payload exceeds the maximum size, anAPNSDataOverflowexception will be raised before anything is sent.
Reference:Apple Payload DocumentationWeb Push accepts only one variable (message), which is passed directly to pywebpush. This message can be a simple string, which will be used as your notification’s body, or it can be containany data supported by pywebpush<https://github.com/web-push-libs/pywebpush>.Simple example:frompush_notifications.modelsimportWebPushDevicedevice=WebPushDevice.objects.get(registration_id=wp_reg_id)device.send_message("You've got mail")NoteTo customize the notification title using this method, edit the"TITLE DEFAULT"string in yournavigatorPush.service.jsfile.JSON example:importjsonfrompush_notifications.modelsimportWebPushDevicedevice=WebPushDevice.objects.get(registration_id=wp_reg_id)title="Message Received"message="You've got mail"data=json.dumps({"title":title,"message":message})device.send_message(data)Sending messages in bulkfrompush_notifications.modelsimportAPNSDevice,GCMDevicedevices=GCMDevice.objects.filter(user__first_name="James")devices.send_message("Happy name day!")Sending messages in bulk makes use of the bulk mechanics offered by GCM and APNS. It is almost always preferable to send
bulk notifications instead of single ones.It’s also possible to pass badge parameter as a function which accepts token parameter in order to set different badge
value per user. Assuming User model has a method get_badge returning badge count for a user:devices.send_message("Happy name day!",badge=lambdatoken:APNSDevice.objects.get(registration_id=token).user.get_badge())Firebase vs Google Cloud Messagingdjango-push-notificationssupports both Google Cloud Messaging and Firebase Cloud Messaging (which is now the officially supported messaging platform from Google). When registering a device, you must pass thecloud_message_typeparameter to set the cloud type that matches the device needs.
This is currently defaulting to'GCM', but may change to'FCM'at some point. You are encouraged to use theofficially supported library.When using FCM,django-push-notificationswill automatically use thenotification and data messages formatto be conveniently handled by Firebase devices. You may want to check the payload to see if it matches your needs, and review your notification statuses inFCM Diagnostic console.# Create a FCM devicefcm_device=GCMDevice.objects.create(registration_id="token",cloud_message_type="FCM",user=the_user)# Send a notification messagefcm_device.send_message("This is a message")# Send a notification message with additionnal payloadfcm_device.send_message("This is a enriched message",extra={"title":"Notification title","icon":"icon_ressource"})# Send a notification message with additionnal payload (alternative syntax)fcm_device.send_message("This is a enriched message",title="Notification title",badge=6)# Send a notification message with extra datafcm_device.send_message("This is a message with data",extra={"other":"content","misc":"data"})# Send a notification message with optionsfcm_device.send_message("This is a message",time_to_live=3600)# Send a data message onlyfcm_device.send_message(None,extra={"other":"content","misc":"data"})You can disable this default behaviour by settinguse_fcm_notificationstoFalse.fcm_device=GCMDevice.objects.create(registration_id="token",cloud_message_type="FCM",user=the_user)# Send a data message with classic formatfcm_device.send_message("This is a message",use_fcm_notifications=False)Sending FCM/GCM messages to topic membersFCM/GCM topic messaging allows your app server to send a message to multiple devices that have opted in to a particular topic. Based on the publish/subscribe model, topic messaging supports unlimited subscriptions per app. Developers can choose any topic name that matches the regular expression, “/topics/[a-zA-Z0-9-_.~%]+”.
Note: gcm_send_bulk_message must be used when sending messages to topic subscribers, and setting the first param to any value other than None will result in a 400 Http error.frompush_notifications.gcmimportsend_message# First param is "None" because no Registration_id is needed, the message will be sent to all devices subscribed to the topic.send_message(None,{"body":"Hello members of my_topic!"},cloud_type="FCM",to="/topics/my_topic")Reference:FCM DocumentationExceptionsNotificationError(Exception): Base exception for all notification-related errors.gcm.GCMError(NotificationError): An error was returned by GCM. This is never raised when using bulk notifications.apns.APNSError(NotificationError): Something went wrong upon sending APNS notifications.apns.APNSDataOverflow(APNSError): The APNS payload exceeds its maximum size and cannot be sent.Django REST Framework (DRF) supportViewSets are available for both APNS and GCM devices in two permission flavors:APNSDeviceViewSetandGCMDeviceViewSetPermissions as specified in settings (AllowAnyby default, which is not recommended)A device may be registered without associating it with a userAPNSDeviceAuthorizedViewSetandGCMDeviceAuthorizedViewSetPermissions areIsAuthenticatedand custom permissionIsOwner, which will only allow therequest.userto get and update devices that belong to that userRequires a user to be authenticated, so all devices will be associated with a userWhen creating anAPNSDevice, theregistration_idis validated to be a 64-character or 200-character hexadecimal string. Since 2016, device tokens are to be increased from 32 bytes to 100 bytes.Routes can be added one of two ways:Routers(include all views)from push_notifications.api.rest_framework import APNSDeviceAuthorizedViewSet, GCMDeviceAuthorizedViewSet
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'device/apns', APNSDeviceAuthorizedViewSet)
router.register(r'device/gcm', GCMDeviceAuthorizedViewSet)

urlpatterns = patterns('',
        # URLs will show up at <api_root>/device/apns
        url(r'^', include(router.urls)),
        # ...
)Usingas_view(specify which views to include)from push_notifications.api.rest_framework import APNSDeviceAuthorizedViewSet

urlpatterns = patterns('',
        # Only allow creation of devices by authenticated users
        url(r'^device/apns/?$', APNSDeviceAuthorizedViewSet.as_view({'post': 'create'}), name='create_apns_device'),
        # ...
)Update of device with duplicate registration IDThe DRF viewset enforce the uniqueness of the registration ID. In same use case it
may cause issue: If an already registered mobile change its user and it will
fail to register because the registration ID already exist.When optionUPDATE_ON_DUPLICATE_REG_IDis set to True, then any creation of
device with an already existing registration ID will be transformed into an update.TheUPDATE_ON_DUPLICATE_REG_IDonly works with DRF.[1]Any devices which are not selected, but are not receiving notifications will not be deactivated on a subsequent call to “prune devices” unless another attempt to send a message to the device fails after the call to the feedback service.