在订阅回调中使用Python客户端lib装饰器

时间:2013-12-07 01:18:00

标签: google-glass google-mirror-api

我一直在GAE上使用Mirror API构建一个小型服务,使用来自Google API Client Library for Python的装饰器来自动化OAuth舞蹈。我在获取订阅通知处理程序时遇到了一些问题,我刚刚意识到通过从处理订阅ping的POST方法中删除装饰器,它可以工作(也就是说我可以输入方法并检查JSON正文)。

这很有意义,因为Mirror API正在调用回调,而不是用户。

但是我仍然需要提出处理有效负载的授权请求,这意味着我需要一个授权的服务对象,所以我需要为这部分手动编写OAuth,否则库会自动获取调用通知的用户的凭据?

感谢您的帮助!

 # leaving the decorator on the method causes it not to work
 # @decorator.oauth_required
 def post(self):

    logging.info('PAYLOAD %s' % self.request.body)

    # get the authorized object created by the decorator
    # this isn't going to work since it's dependent on the decorator
    http = decorator.http()

    # handle the inbound JSON payload from the body of the request via POST
    data = json.load(self.request.body)
    item_id = data["itemId"]
    user_id  = data["userToken"]
    update_item = mirror_api_service.timeline().get(id=item_id).execute(http=http)

    for user_action in data.get('userActions',[]):
        if user_action.get('type') == 'LAUNCH':

            speakable_text = "Echoing your speech input: " % update_item["text"]

            card_content = {
                "text": speakable_text,
                "speakableText": speakable_text,
                "notification": { "level": "DEFAULT" }
            }

            try:
                mirror_api_service.timeline().insert(body=card_content).execute(http=http)      
                self.response.set_status(200)
            except errors.HttpError, error:
                logging.warn('PROBLEM: ' + str(error))  

            # only process the first userAction
            break

1 个答案:

答案 0 :(得分:0)

您需要加载凭据并使用它来创建API客户端。以下是Python quick start的代码段。

  def post(self):
    """Handles notification pings."""
    logging.info('Got a notification with payload %s', self.request.body)
    data = json.loads(self.request.body)
    userid = data['userToken']

    self.mirror_service = util.create_service(
        'mirror', 'v1',
        StorageByKeyName(Credentials, userid, 'credentials').get())

    if data.get('collection') == 'locations':
      self._handle_locations_notification(data)
    elif data.get('collection') == 'timeline':
      self._handle_timeline_notification(data)