Created
July 24, 2014 15:45
-
-
Save jancajthaml/476cb72af461602017f4 to your computer and use it in GitHub Desktop.
Python GCM Client
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
# Quick and Dirty DRAFT for Google Cloud Messaging REST by Petnik | |
import random | |
import requests | |
import json | |
api_key = 'XXXXXXXxXXXXXXXxXXXXXXXxXXXXXXXx' | |
gateway = 'https://android.googleapis.com/gcm/send' | |
################## | |
custom_data = { | |
'foo': 'bar' | |
} | |
reg_id = ['a','b','c'] | |
headers = { | |
'Authorization' : 'key=%s' % api_key, | |
'Content-Type' : 'application/json' | |
} | |
payload = { | |
'data' : custom_data, | |
'registration_ids' : reg_id | |
} | |
data = json.dumps( payload, separators=(',',':'), ensure_ascii=False).encode('utf-8') | |
response = requests.post(gateway, data=data, headers=headers ) | |
#todo accept content type json | |
if response.status_code == 400 : raise ValueError(response.content) | |
if response.status_code == 401 : raise Exception("Authentication Error") | |
if response.status_code == 200 or (response.status_code >= 500 and response.status_code <= 599) : | |
response = json.loads(response.text) | |
if 'results' not in response or len(response['results']) != len(reg_id) : raise ValueError("Invalid response") | |
for token, res in zip(reg_id, response['results']) : | |
if 'message_id' in res : | |
print "OK ( %s )" % token | |
else : | |
if res['error'] == "Unavailable" or res['error'] == "InternalServerError" : | |
print "Unavailable ( %s )" % token | |
elif res['error'] == "NotRegistered" or res['error'] == 'InvalidRegistration' : | |
print "Not Registered ( %s )" % token | |
else : | |
from pprint import pprint | |
print "Token ( %s ) errors :" % token | |
pprint(res['error']) | |
# END GCM DRAFT |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment