Sending iOS Push Notifications using Python module PyAPNS

No comments on Sending iOS Push Notifications using Python module PyAPNS

python-django

I have written a small module, that sends a push notification using PyAPNS.

This is how my sender.py module looks like:

# -*- coding: utf-8 -*-
from django.db import connection
from apns import APNs, Frame, Payload


class Sender:
	def send(self):
		apns = APNs(use_sandbox=True, cert_file='Cert.pem', key_file='Key.pem')
		token_hex = 'e4d4e96ec8ac3dd003e0129347b3421fe53ba49811b3803c4e99cfdc60293c94'
		message = "Hello"
		payload = Payload(alert=message.decode('utf-8'), sound="default", badge=0)
		apns.gateway_server.send_notification(token_hex, payload)

Here is a Sender class inside sender.py module. It has one method send. Inside this method I create an object of APNs class, create a payload and send it using this object.
Cert.pem and Key.pem files are inside the folder with this module. They can be created using this tutorial. Also that folder contains apns.py module file with PyAPNS code.

To send a sample push notification from a command line I use following commands. First, I enter the folder with module. It is called notification_sender:

$ cd ~/Documents/common-app-server/app_server/notification_sender

Or on server:

# cd ~/www/den.ladby.ru/public/common-app-server/app_server/notification_sender

Then I enter to the python console:

$ python

Then I import Sender class from sender module:

from sender import Sender

Create a sender object of a Sender class:

sender = Sender()

And finally send a notification:

sender.send()

All you need to do to finish the job is to enter a PEM pass phrase:

Enter PEM pass phrase:

Currently, the device token is hardcoded, I am planning to use SQLite entries with collected tokens. I use Django to collect tokens.

I would like to add that if you change somehow the source file of a module, you should reenter python console and recreate object to make changes work.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *