aws boto sns - get endpoint_arn by device token

試著忘記壹切 提交于 2019-12-06 02:12:35

问题


Currently, If we want to add a device to an SNS application using:

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

There is an option that the device was already added in the past. To verify if the device is already added, we're using:

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

which is very inefficient and can not be scaled.

is there a boto sns function that get the device_token and returns the endpoint_arn if exists? (None if not).


回答1:


Amazon gives you the arn on the Error Message. You can parse it from there. Not optimal, but saves some db lookup.

error: SNS ERROR - Could not subcribe user to SNSInvalidParameter: Invalid parameter: Token Reason: Endpoint arn:aws:sns:us-east-[rest of the ARN Key] already exists with the same Token, but different attributes. Here is some coffe with regex ready to go

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} "



回答2:


Same answer as @fino but code for Django. Hope this help.

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 ''


来源:https://stackoverflow.com/questions/22227262/aws-boto-sns-get-endpoint-arn-by-device-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!