djacobs / PyAPNs

Python library for interacting with the Apple Push Notification service (APNs)
http://pypi.python.org/pypi/apns/
MIT License
1.22k stars 374 forks source link

PyAPNs

A Python library for interacting with the Apple Push Notification service (APNs)

Installation

Either download the source from GitHub or use easy_install:

$ easy_install apns

Sample usage

import time
from apns import APNs, Frame, Payload

apns = APNs(use_sandbox=True, cert_file='cert.pem', key_file='key.pem')

# Send a notification
token_hex = 'b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b87'
payload = Payload(alert="Hello World!", sound="default", badge=1)
apns.gateway_server.send_notification(token_hex, payload)

# Send an iOS 10 compatible notification
token_hex = 'b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b87'
payload = Payload(alert="Hello World!", sound="default", badge=1, mutable_content=True)
apns.gateway_server.send_notification(token_hex, payload)

# Send multiple notifications in a single transmission
frame = Frame()
identifier = 1
expiry = time.time()+3600
priority = 10
frame.add_item('b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b87', payload, identifier, expiry, priority)
apns.gateway_server.send_notification_multiple(frame)

Apple recommends to query the feedback service daily to get the list of device tokens. You need to create a new connection to APNS to see all the tokens that have failed since you only receive that information upon connection. Remember, once you have viewed the list of tokens, Apple will clear the list from their servers. Use the timestamp to verify that the device tokens haven’t been reregistered since the feedback entry was generated. For each device that has not been reregistered, stop sending notifications. By using this information to stop sending push notifications that will fail to be delivered, you reduce unnecessary message overhead and improve overall system performance.

#New APNS connection
feedback_connection = APNs(use_sandbox=True, cert_file='cert.pem', key_file='key.pem')

# Get feedback messages.
for (token_hex, fail_time) in feedback_connection.feedback_server.items():
    # do stuff with token_hex and fail_time

For more complicated alerts including custom buttons etc, use the PayloadAlert class. Example:

alert = PayloadAlert("Hello world!", action_loc_key="Click me")
payload = Payload(alert=alert, sound="default")

To send custom payload arguments, pass a dictionary to the custom kwarg of the Payload constructor.

payload = Payload(alert="Hello World!", custom={'sekrit_number':123})

Enhanced Message with immediate error-response

apns_enhanced = APNs(use_sandbox=True, cert_file='apns.pem', enhanced=True)

Send a notification. note that identifer is the information to indicate which message has error in error-response payload, it should be UNIQUE since PyAPNs will also use it to determine the range of messages to be re-sent.

token_hex = 'b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b87'
payload = Payload(alert="Hello World!", sound="default", badge=1)
identifier = random.getrandbits(32)
apns_enhanced.gateway_server.send_notification(token_hex, payload, identifier=identifier)

Callback when error-response occur, with parameter {'status': <status code from APNS>, 'identifier': <the identifier specified>} Status code reference

def response_listener(error_response):
    _logger.debug("client get error-response: " + str(error_response))

apns_enhanced.gateway_server.register_response_listener(response_listener)

Error response worker will be auto-close after 30 secs idle of connection operations. If you want disable APNS connection and error-responses handler immediately, force_close it.

apns_enhanced.gateway_server.force_close()

Extra log messages when error-response occur, auto-resent afterwards.

got error-response from APNS:(8, 1)
rebuilding connection to APNS
resending 9 notifications to APNS
resending notification with id:2 to APNS
resending notification with id:3 to APNS
resending notification with id:4 to APNS

Caveats:

Problem Addressed (Reference to Redth):

Solution:

Result:

Test

Travis Build Status

Build Status

Further Info

iOS Reference Library: Local and Push Notification Programming Guide

License

PyAPNs is distributed under the terms of the MIT license.

See LICENSE file for the complete license details.

Credits

Written and maintained by Simon Whitaker at Goo Software Ltd.