aws boto sns - 按设备令牌获取endpoint_arn

时间:2014-03-06 14:22:45

标签: amazon-web-services boto amazon-sns

目前,如果我们想使用以下方法将设备添加到SNS应用程序:

ep = SNSConnection.create_platform_endpoint(app_arn,device_token,user_data)

有一个选项,过去已添加该设备。 要验证设备是否已添加,我们正在使用:

def is_device_registered(device_token):
        list_of_endpoints = SNSConnection.list_endpoints_by_platform_application(AC.INPLAY_CHAT_APPLICATION_SNS_ARN)
        all_app_endpoints = list_of_endpoints['ListEndpointsByPlatformApplicationResponse']['ListEndpointsByPlatformApplicationResult']['Endpoints']
        for ep in all_app_endpoints:
            ep_device_token = ep['Attributes']['Token']
            if device_token == ep_device_token:
                endpoint_arn =  ep['EndpointArn']
                print 'Found an endpoint for device_token: %s, entry:%s' % (device_token,endpoint_arn)
                return endpoint_arn
        return None

这是非常低效的,无法缩放。

是否有一个boto sns函数获取device_token并返回endpoint_arn(如果存在)? (如果没有,则无。)

2 个答案:

答案 0 :(得分:6)

亚马逊为您提供错误消息的arn。你可以从那里解析它。不是最佳的,但保存了一些数据库查找。

错误:SNS错误 - 无法将用户订阅到SNSInvalidParameter:无效参数:令牌原因:端点arn:aws:sns:us-east- [ARN Key的其余部分]已经存在相同的令牌,但属性不同。这是一些准备好正规的咖啡

if err?
  log.error "SNS ERROR - Could not subcribe user to SNS" + err
  #Try to get arn from error

  result = err.message.match(/Endpoint(.*)already/)
  if result?.length
    #Assign and remove leading and trailing white spaces.
    result = result[1].replace /^\s+|\s+$/g, ""
    log.debug "found existing arn-> #{result} "

答案 1 :(得分:5)

与@fino相同的答案,但Django的代码。希望这有帮助。

import re

try:
    sns_connection = sns.connect_to_region(...)
    response = sns_connection.create_platform_endpoint(...)
    arn = response['CreatePlatformEndpointResponse']['CreatePlatformEndpointResult']['EndpointArn']
    return arn

except Exception, err:
    print err
    #try to get arn from error
    result_re = re.compile(r'Endpoint(.*)already', re.IGNORECASE)
    result = result_re.search(err.message)
    if result:
        arn = result.group(0).replace('Endpoint ','').replace(' already','')
        print arn
        return arn
    return ''