Last active
August 31, 2018 11:31
-
-
Save symstu/75ad2f6f9738f54aa2ec6b81e81d0f7e to your computer and use it in GitHub Desktop.
Send direct push notification on ios via Amazon SNS with boto module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import boto.sns | |
class AmazonSNSIosPush: | |
def __init__(self, region_name, aws_access_key_id, | |
aws_secret_access_key, arn): | |
self.user_token = None | |
self.message = None | |
self.arn = arn | |
self.client = boto.sns.connect_to_region( | |
region_name=region_name, | |
aws_access_key_id=aws_access_key_id, | |
aws_secret_access_key=aws_secret_access_key | |
) | |
def __enter__(self): | |
return self | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
if not self.message: | |
raise ValueError('Message can not be empty') | |
endpoint_response = self.client.create_platform_endpoint( | |
platform_application_arn=self.arn, token=self.user_token | |
) | |
endpoint_arn = endpoint_response['CreatePlatformEndpointResponse'][ | |
'CreatePlatformEndpointResult']['EndpointArn'] | |
params = { | |
'target_arn': endpoint_arn, | |
'message': self.create_message(self.message), | |
'message_structure': 'json' | |
} | |
self.client.publish(**params) | |
@staticmethod | |
def create_message(data): | |
return json.dumps(dict( | |
APNS=json.dumps(data), | |
default=json.dumps(dict()) | |
)) | |
with AmazonSNSIosPush('region', 'access_key', 'secret_key', 'arn') as sns: | |
sns.message = dict( | |
aps=dict( | |
alert='Hello there', sound='default' | |
), | |
) | |
sns.user_token = 'ios device registration token' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment