Last active
August 29, 2015 13:57
-
-
Save lovesh/9491911 to your computer and use it in GitHub Desktop.
GCM wrapper in python using python requests. Allows sending message to multiple senders
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 requests | |
import simplejson as json | |
import os | |
class GCMMultiRequest(object): | |
def __init__(self, gcm_url, headers): | |
self.gcm_url = gcm_url | |
self.headers = headers | |
self.session = requests.Session() | |
def send(self, data, reg_ids): | |
self.reg_ids = reg_ids | |
data['registration_ids'] = self.reg_ids | |
jdata = json.dumps(data) | |
self.data = jdata.replace('\\\\', '\\') | |
tries = 0 | |
while tries < 2: | |
try: | |
response = self.session.post(self.gcm_url, headers=self.headers, data=self.data) | |
break | |
except (requests.exceptions.ConnectionError, requests.exceptions.SSLError) as e: | |
tries += 1 | |
if tries == 2: | |
raise e | |
tries = 0 | |
while tries < 2: | |
try: | |
content = json.loads(response.content) | |
break | |
except json.decoder.JSONDecodeError as e: | |
tries += 1 | |
if tries == 2: | |
raise e | |
self.multicast_id = content['multicast_id'] | |
self.success = content['success'] | |
self.failure = content['failure'] | |
self.canonical_ids = content['canonical_ids'] | |
results = content['results'] | |
self.results = [] | |
for r_id, result in zip(self.reg_ids, results): | |
if 'error' in result: | |
self.results.append({'reg_id': r_id, 'error': result['error']}) | |
continue | |
if 'message_id' in result: | |
if 'registration_id' in result: | |
self.results.append({'reg_id': r_id, 'new_reg_id': result['registration_id']}) | |
else: | |
self.results.append({'reg_id': r_id}) | |
return response | |
__all__ = ['GCMMultiRequest'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment