API Reference

APNS

Client module for Apple Push Notification service.

The algorithm used to send bulk push notifications is optimized to eagerly check for errors using a single thread. Error checking is performed after each batch send (bulk notifications may be broken up into multiple batches) and is non-blocking until the last notification is sent. A final, blocking error check is performed using a customizable error timeout. This style of error checking is done to ensure that no errors are missed (e.g. by waiting too long to check errors before the connection is closed by the APNS server) without having to use two threads to read and write.

The return from a send operation will contain a response object that includes any errors encountered while sending. These errors will be associated with the failed tokens.

For more details regarding Apple’s APNS documentation, consult the following:

class pushjack.apns.APNSClient(certificate, default_error_timeout=10, default_expiration_offset=2592000, default_batch_size=100, default_max_payload_length=0, default_retries=5)

APNS client class.

close()

Close APNS connection.

conn

Reference to lazy APNS connection.

create_connection()

Create and return new APNS connection to push server.

create_feedback_connection()

Create and return new APNS connection to feedback server.

get_expired_tokens()

Return inactive device tokens that are no longer registered to receive notifications.

Returns:List of APNSExpiredToken instances.
Return type:list

New in version 0.0.1.

send(ids, message=None, expiration=None, low_priority=None, batch_size=None, error_timeout=None, max_payload_length=None, retries=None, **options)

Send push notification to single or multiple recipients.

Parameters:
  • ids (list) – APNS device tokens. Each item is expected to be a hex string.
  • message (str|dict) – Message string or APS dictionary. Set to None to send an empty alert notification.
  • expiration (int, optional) – Expiration time of message in seconds offset from now. Defaults to None which uses default_expiration_offset.
  • low_priority (boolean, optional) – Whether to send notification with the low priority flag. Defaults to False.
  • batch_size (int, optional) – Number of notifications to group together when sending. Defaults to None which uses attr:default_batch_size.
  • error_timeout (int, optional) – Time in seconds to wait for the error response after sending messages. Defaults to None which uses attr:default_error_timeout.
  • max_payload_length (int, optional) – The maximum length of the payload to send. Message will be trimmed if the size is exceeded. Use 0 to turn off. Defaults to None which uses attr:default_max_payload_length.
  • retries (int, optional) – Number of times to retry when the send operation fails. Defaults to None which uses default_retries.
Keyword Arguments:
 
  • badge (int, optional) – Badge number count for alert. Defaults to None.
  • sound (str, optional) – Name of the sound file to play for alert. Defaults to None.
  • category (str, optional) – Name of category. Defaults to None.
  • content_available (bool, optional) – If True, indicate that new content is available. Defaults to None.
  • title (str, optional) – Alert title.
  • title_loc_key (str, optional) – The key to a title string in the Localizable.strings file for the current localization.
  • title_loc_args (list, optional) – List of string values to appear in place of the format specifiers in title_loc_key.
  • action_loc_key (str, optional) – Display an alert that includes the Close and View buttons. The string is used as a key to get a localized string in the current localization to use for the right button’s title instead of "View".
  • loc_key (str, optional) – A key to an alert-message string in a Localizable.strings file for the current localization.
  • loc_args (list, optional) – List of string values to appear in place of the format specifiers in loc_key.
  • launch_image (str, optional) – The filename of an image file in the app bundle; it may include the extension or omit it.
  • mutable_content (bool, optional) – if True, triggers Apple Notification Service Extension. Defaults to None.
  • thread_id (str, optional) – Identifier for grouping notifications. iOS groups notifications with the same thread identifier together in Notification Center. Defaults to None.
  • extra (dict, optional) – Extra data to include with the alert.
Returns:

Response from APNS containing tokens sent

and any errors encountered.

Return type:

APNSResponse

Raises:

New in version 0.0.1.

Changed in version 0.4.0: - Added support for bulk sending. - Made sending and error checking non-blocking. - Removed sock, payload, and identifer arguments.

Changed in version 0.5.0: - Added batch_size argument. - Added error_timeout argument. - Replaced priority argument with low_priority=False. - Resume sending notifications when a sent token has an error response. - Raise APNSSendError if any tokens have an error response.

Changed in version 1.0.0: - Return APNSResponse instead of raising APNSSendError. - Raise APNSMissingPayloadError if payload is empty.

Changed in version 1.4.0: Added retries argument.

class pushjack.apns.APNSSandboxClient(certificate, default_error_timeout=10, default_expiration_offset=2592000, default_batch_size=100, default_max_payload_length=0, default_retries=5)

APNS client class for sandbox server.

class pushjack.apns.APNSResponse(tokens, message, errors)

Response from APNS after sending tokens.

tokens

list – List of all tokens sent during bulk sending.

message

APNSMessageAPNSMessage object sent.

errors

list – List of APNS exceptions for each failed token.

failures

list – List of all failed tokens.

successes

list – List of all successful tokens.

token_errors

dict – Dict mapping the failed tokens to their respective APNS exception.

New in version 1.0.0.

class pushjack.apns.APNSExpiredToken

Represents an expired APNS token with the timestamp of when it expired.

token

str – Expired APNS token.

timestamp

int – Epoch timestamp.

Exceptions

The APNSServerError class of exceptions represent error responses from APNS. These exceptions will contain attributes for code, description, and identifier. The identifier attribute is the list index of the token that failed. However, none of these exceptions will be raised directly. Instead, APNS server errors are collected and packaged into a APNSResponse object and returned by APNSClient.send(). This object provides a list of the raw exceptions as well as a mapping of the actual token and its associated error.

Below is a listing of APNS Server exceptions:

Exception Code Description
APNSProcessingError 1 Processing error
APNSMissingTokenError 2 Missing token
APNSMissingTopicError 3 Missing topic
APNSMissingPayloadError 4 Missing payload
APNSInvalidTokenSizeError 5 Invalid token size
APNSInvalidTopicSizeError 6 Invalid topic size
APNSInvalidPayloadSizeError 7 Invalid payload size
APNSInvalidTokenError 8 Invalid token
APNSShutdownError 10 Shutdown
APNSUnknownError 255 Unknown
class pushjack.exceptions.APNSError

Base exception for APNS errors.

class pushjack.exceptions.APNSAuthError

Exception with APNS certificate.

class pushjack.exceptions.APNSServerError(identifier)

Base exception for APNS Server errors.

class pushjack.exceptions.APNSProcessingError(identifier)

Exception for APNS processing error.

class pushjack.exceptions.APNSMissingTokenError(identifier)

Exception for APNS missing token error.

class pushjack.exceptions.APNSMissingTopicError(identifier)

Exception for APNS missing topic error.

class pushjack.exceptions.APNSMissingPayloadError(identifier)

Exception for APNS payload error.

class pushjack.exceptions.APNSInvalidTokenSizeError(identifier)

Exception for APNS invalid token size error.

class pushjack.exceptions.APNSInvalidTopicSizeError(identifier)

Exception for APNS invalid topic size error.

class pushjack.exceptions.APNSInvalidPayloadSizeError(identifier)

Exception for APNS invalid payload size error.

class pushjack.exceptions.APNSInvalidTokenError(identifier)

Exception for APNS invalid token error.

class pushjack.exceptions.APNSShutdownError(identifier)

Exception for APNS shutdown error.

class pushjack.exceptions.APNSUnknownError(identifier)

Exception for APNS unknown error.

GCM

Client module for Google Cloud Messaging service.

By default, sending notifications is optimized to deliver notifications to the maximum number of allowable recipients per HTTP request (currently 1,000 recipients as specified in the GCM documentation).

The return from a send operation will contain a response object that parses all GCM HTTP responses and groups them by errors, successful registration ids, failed registration ids, canonical ids, and the raw responses from each request.

For more details regarding Google’s GCM documentation, consult the following:

class pushjack.gcm.GCMClient(api_key)

GCM client class.

conn

Reference to lazy GCM connection.

create_connection()

Create and return new GCM connection.

send(ids, message, **options)

Send push notification to single or multiple recipients.

Parameters:
  • ids (list) – GCM device registration IDs.
  • message (str|dict) – Message string or dictionary. If message is a dict and contains the field notification, then it will be used for the notification payload.
Keyword Arguments:
 
  • notificatoin (dict, optional) – Notification payload. Can include the fields body, title, and icon.
  • collapse_key (str, optional) – Identifier for a group of messages that can be collapsed so that only the last message gets sent when delivery can be resumed. Defaults to None.
  • delay_while_idle (bool, optional) – If True indicates that the message should not be sent until the device becomes active.
  • time_to_live (int, optional) – How long (in seconds) the message should be kept in GCM storage if the device is offline. The maximum time to live supported is 4 weeks. Defaults to None which uses the GCM default of 4 weeks.
  • low_priority (boolean, optional) – Whether to send notification with the low priority flag. Defaults to False.
  • restricted_package_name (str, optional) – Package name of the application where the registration IDs must match in order to receive the message. Defaults to None.
  • dry_run (bool, optional) – If True no message will be sent but request will be tested.
Returns:

Response from GCM server.

Return type:

GCMResponse

Raises:

GCMAuthError – If api_key not set. GCMAuthError

New in version 0.0.1.

Changed in version 0.4.0: - Added support for bulk sending. - Removed request argument.

Changed in version 1.2.0: - Added low_priority argument.

class pushjack.gcm.GCMResponse(responses)

GCM server response with results parsed into responses, messages, registration_ids, data, successes, failures, errors, and canonical_ids.

responses

list – List of requests.Response objects from each GCM request.

messages

list – List of message data sent in each GCM request.

registration_ids

list – Combined list of all recipient registration IDs.

data

list – List of each GCM server response data.

successes

list – List of registration IDs that were sent successfully.

failures

list – List of registration IDs that failed.

errors

list – List of exception objects correponding to the registration IDs that ere not sent successfully. See pushjack.exceptions.

canonical_ids

list – List of registration IDs that have been reassigned a new ID. Each element is an instance of GCMCanonicalID.

class pushjack.gcm.GCMCanonicalID

Represents a canonical ID returned by the GCM Server. This object indicates that a previously registered ID has changed to a new one.

old_id

str – Previously registered ID.

new_id

str – New registration ID that should replace old_id.

Exceptions

The GCMServerError class of exceptions are contained in GCMResponse.errors. Each exception contains attributes for code, description, and identifier (i.e. the registration ID that failed).

Below is a listing of GCM Server exceptions:

Exception Code Description
GCMMissingRegistrationError MissingRegistration Missing registration ID
GCMInvalidRegistrationError InvalidRegistration Invalid registration ID
GCMUnregisteredDeviceError NotRegistered Device not registered
GCMInvalidPackageNameError InvalidPackageName Invalid package name
GCMMismatchedSenderError MismatchSenderId Mismatched sender ID
GCMMessageTooBigError MessageTooBig Message too big
GCMInvalidDataKeyError InvalidDataKey Invalid data key
GCMInvalidTimeToLiveError InvalidTtl Invalid time to live
GCMTimeoutError Unavailable Timeout
GCMInternalServerError InternalServerError Internal server error
GCMDeviceMessageRateExceededError DeviceMessageRateExceeded Message rate exceeded
class pushjack.exceptions.GCMError

Base exception for GCM errors.

class pushjack.exceptions.GCMAuthError

Exception for error with GCM API key.

class pushjack.exceptions.GCMServerError(identifier)

Base exception for GCM Server errors.

class pushjack.exceptions.GCMMissingRegistrationError(identifier)

Exception for missing registration ID.

class pushjack.exceptions.GCMInvalidRegistrationError(identifier)

Exception for invalid registration ID

class pushjack.exceptions.GCMUnregisteredDeviceError(identifier)

Exception for unregistered device.

class pushjack.exceptions.GCMInvalidPackageNameError(identifier)

Exception for invalid package name.

class pushjack.exceptions.GCMMismatchedSenderError(identifier)

Exception for mismatched sender.

class pushjack.exceptions.GCMMessageTooBigError(identifier)

Exception for message too big.

class pushjack.exceptions.GCMInvalidDataKeyError(identifier)

Exception for invalid data key.

class pushjack.exceptions.GCMInvalidTimeToLiveError(identifier)

Exception for invalid time to live.

class pushjack.exceptions.GCMTimeoutError(identifier)

Exception for server timeout.

class pushjack.exceptions.GCMInternalServerError(identifier)

Exception for internal server error.

class pushjack.exceptions.GCMDeviceMessageRateExceededError(identifier)

Exception for device message rate exceeded.

Logging

Internal logging is handled with the logging module. The logger names used are:

  • pushjack
  • pushjack.apns
  • pushjack.gcm

Enabling

To enable logging using an imperative approach:

import logging
import pushjack

logger = logging.getLogger('pushjack')
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)

logger.addHandler(stream_handler)

To enable logging using a configuration approach:

import logging
import logging.config
import pushjack

logging.config.dictConfig({
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'level': 'DEBUG'
        }
    },
    'loggers': {
        'pushjack': {
            'handlers': ['console']
        }
    }
})

For additional configuration options, you may wish to install logconfig:

pip install logconfig
import logconfig
import pushjack

logconfig.from_yaml('path/to/logconfig.yml')