· 7 years ago · Aug 31, 2018, 02:40 PM
1import json
2import boto.sns
3
4
5class AmazonSNSIosPush:
6 def __init__(self, region_name, aws_access_key_id,
7 aws_secret_access_key, arn):
8 self.user_token = None
9 self.message = None
10 self.arn = arn
11
12 self.client = boto.sns.connect_to_region(
13 region_name=region_name,
14 aws_access_key_id=aws_access_key_id,
15 aws_secret_access_key=aws_secret_access_key
16 )
17
18 def __enter__(self):
19 return self
20
21 def __exit__(self, exc_type, exc_val, exc_tb):
22 if not self.message:
23 raise ValueError('Message can not be empty')
24
25 endpoint_response = self.client.create_platform_endpoint(
26 platform_application_arn=self.arn, token=self.user_token
27 )
28 endpoint_arn = endpoint_response['CreatePlatformEndpointResponse'][
29 'CreatePlatformEndpointResult']['EndpointArn']
30
31 params = {
32 'target_arn': endpoint_arn,
33 'message': self.create_message(self.message),
34 'message_structure': 'json'
35 }
36 self.client.publish(**params)
37
38 @staticmethod
39 def create_message(data):
40 return json.dumps(dict(
41 APNS=json.dumps(data),
42 default=json.dumps(dict())
43 ))
44
45
46with AmazonSNSIosPush('region', 'access_key', 'secret_key', 'arn') as sns:
47 sns.message = dict(
48 aps=dict(
49 alert='Hello there', sound='default'
50 ),
51 )
52 sns.user_token = 'ios device registration token'