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

Ami*_*mor 5 boto amazon-web-services amazon-sns

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

ep = SNSConnection.create_platform_endpoint(app_arn,device_token,user_data)
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

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

fin*_*ino 6

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

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

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} "
Run Code Online (Sandbox Code Playgroud)

  • 这不是很荒谬吗?如果错误的格式发生变化怎么办? (3认同)

Joh*_*ang 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 ''
Run Code Online (Sandbox Code Playgroud)