问题
I'm using Apache, WSGI (mod_wsgi) and Python, to implement a GCM HTTP server as describe in the Android Developer website:
developer.android.com/google/gcm/server.html
At first the code I've implemented on the server side to handle message sending to GCM was as the following:
def send_to_gcm(data):
url = 'https://android.googleapis.com/gcm/send'
no = 1
while True:
try:
request = Request(url=url, data=json.dumps(data))
request.add_header('Authorization','key=AIzXXX')
request.add_header('Content-Type', 'application/json')
res = urlopen(request)
if res.getcode() == 200: return
except Exception: pass
no += 1
#Discard the message
if no == 16: return
#Exponential backoff
tts = randint(2**(no-1), (2**no) -1)
sleep(tts)
data = dict(registration_id=[regid], data=dict(mymessage=themessage))
thread = Thread(target=send_to_gcm, args=(data,))
thread.start()
After a while (about a day) GCM stopped to accept the messages sent by the Server. So I started to dig here and there in the documentation of GCM and I found an important part of the specification I missed before:
developer.android.com/google/gcm/http.html#response
"Honor the Retry-After header if it's included in the response from the GCM server. ... Senders that cause problems risk being blacklisted. ... Happens when the HTTP status code is between 501 and 599, or when the error field of a JSON object in the results array is Unavailable."
So i patched my server code as follow:
def send_to_gcm(data, environ):
url = 'https://android.googleapis.com/gcm/send'
no = 1
while True:
try:
request = Request(url=url, data=json.dumps(data))
request.add_header('Authorization','key=AIzXXX')
request.add_header('Content-Type', 'application/json')
res = urlopen(request)
if res.getcode() == 200: return
except HTTPError as error:
if error.headers.has_key('Retry-After'):
try: tts = int(response_headers['Retry-After'])
except ValueError:
until = datetime.strptime(response_headers, '%a, %d %b %Y %H:%M:%S GMT')
diff = until - datetime.now()
tts = int(diff.total_seconds()) +1
sleep(tts)
no += 1
#Discard the message
if no == 16: return
#Exponential backoff
tts = randint(2**(no-1), (2**no) -1)
sleep(tts)
But actually it's likely my server has been blacklisted and for any request sent I receive a 401 status code and an "Unauthorized" error message. Here my questions:
Is there something wrong in my latest server implementation?
Will the static IP address of my server be unbanned and if yes when?
回答1:
I was searching for the same subject. This module may help you https://github.com/geeknam/python-gcm
来源:https://stackoverflow.com/questions/23720564/how-to-implement-gcm-http-server-in-python-while-avoiding-my-servers-ip-being-b