2015-01-04 3 views
0

Я всегда получаю пустой ответ json {}, когда пытаюсь отправить сообщение через GCM.Пустой ответ json с использованием python-gcm

Я использую python-gcm и это мой код:

from gcm import GCM 

API_KEY = "AldaSyAwnh5jAAAAAAABvBTyqDdMITCoEE8GLZ" 
my_gcm = GCM(api_key=API_KEY) 
data = {'param1': 'value1', 'param2': 'value2'} 


# JSON request 
#reg_ids = ['12', '34', '69'] 
reg_ids = ['ALA91bE9QSkVKcmAAAAAAda8UsNs27R-29pJHDqwIiwqxSAStmhpFo2hKD0SipoCjgANvFJ7trdQZuJCjMaUAAAA6zmETYDncD9YTiVZ61eG1pwXdOJC7mozlt76OoyM81OasWi9_ibGklNfhWGhJpg'] 
response = my_gcm.json_request(registration_ids=reg_ids, data=data) 

# Handling errors 
if 'errors' in response: 
    for error, reg_ids in response['errors'].items(): 
     # Check for errors and act accordingly 
     if error is 'NotRegistered': 
      # Remove reg_ids from database 
      for reg_id in reg_ids: 
       entity.filter(registration_id=reg_id).delete() 

if 'canonical' in response: 
    for reg_id, canonical_id in response['canonical'].items(): 
     # Repace reg_id with canonical_id in your database 
     entry = entity.filter(registration_id=reg_id) 
     entry.registration_id = canonical_id 
     entry.save() 

Что я делаю неправильно, я должен попробовать другой вариант? Дополнительная информация:

  • Я использую колбу.
  • В моей консоли разработчика Google есть карты google

    активировано тоже.

+0

@MartijnPieters является ofuscated, просто для быть уверены, что я использую правильные значения. – Ricardo

+0

Хорошо, но это было непонятно из того, что вы опубликовали. :-) –

ответ

0

Похоже, что использовать python-gcm нельзя. Затем, в соответствии с:

И примите во внимание флаг dry_run=True для тестирования. Следующий код работает как шарм :)

from flask import Flask 
app = Flask(__name__) 

from flask.ext.gcm import GCM 
API_KEY = "AldaSyAwnh5jAAAAAAABvBTyqDdMITCoEE8GLZ" 
gcm = GCM() 
app.config['GCM_KEY'] = API_KEY 
gcm.init_app(app) 

data = {'param1': 'value1', 'param2': 'value2'} 

multicast = JSONMessage(["ALA91bE9QSkVKcmAAAAAAda8UsNs27R-29pJHDqwIiwqxSAStmhpFo2hKD0SipoCjgANvFJ7trdQZuJCjMaUAAAA6zmETYDncD9YTiVZ61eG1pwXdOJC7mozlt76OoyM81OasWi9_ibGklNfhWGhJpg"], data, collapse_key='my.key', dry_run=False) 

try: 
    # attempt send 
    res_multicast = gcm.send(multicast) 

for res in [res_multicast]: 
    # nothing to do on success 
    for reg_id, msg_id in res.success.items(): 
     print "Successfully sent %s as %s" % (reg_id, msg_id) 

    # update your registration ID's 
    for reg_id, new_reg_id in res.canonical.items(): 
     print "Replacing %s with %s in database" % (reg_id, new_reg_id) 

    # probably app was uninstalled 
    for reg_id in res.not_registered: 
     print "Removing %s from database" % reg_id 

    # unrecoverably failed, these ID's will not be retried 
    # consult GCM manual for all error codes 
    for reg_id, err_code in res.failed.items(): 
     print "Removing %s because %s" % (reg_id, err_code) 

    # if some registration ID's have recoverably failed 
    if res.needs_retry(): 
     # construct new message with only failed regids 
     retry_msg = res.retry() 
     # you have to wait before attemting again. delay() 
     # will tell you how long to wait depending on your 
     # current retry counter, starting from 0. 
     print "Wait or schedule task after %s seconds" % res.delay(retry) 
     # retry += 1 and send retry_msg again 

except GCMAuthenticationError: 
    # stop and fix your settings 
    print "Your Google API key is rejected" 
except ValueError, e: 
    # probably your extra options, such as time_to_live, 
    # are invalid. Read error message for more info. 
    print "Invalid message/option or invalid GCM response" 
    print e.args[0] 
except Exception: 
    # your network is down or maybe proxy settings 
    # are broken. when problem is resolved, you can 
    # retry the whole message. 
    print "Something wrong with requests library" 
+0

Эй, я пытаюсь реализовать это сейчас, все, кажется, проходит хорошо, и я получаю успешные ответы назад, но я все еще не вижу push-сообщений, которые будут устройствами. Есть идеи? Кажется, что все настроено отлично, ключ API, код и т. Д. – parchambeau

+0

@parchambeau Вы установили dry_run = False? – Ricardo

Смежные вопросы