Terminal association from the server side to Amazon SNS (python + boto3)

Task

If you want to link a terminal to topic to SNS, there is an example of directly accessing SNS from a smartphone terminal using sdk, but considering the future (such as managing tokens on the dynamoDB side as well), the server When I tried to do it on the side side, there were surprisingly few cases, so I summarized it.

This time, the push notification target is a smartphone, so that is the premise. Also, I'm implementing it in Lambda, but I don't think it depends on Lambda.

Overview

handler.py


import boto3

def lambda_handler(event, context):

    application_arn = 'arn:aws:sns:us-east-1:999999999999:notify_sample'
    topic_arn       = 'arn:aws:sns:us-east-1:999999999999:notify_sample'

    endpoint = add_endpoint(application_arn, token)
    subscribe_token(topic_arn, endpoint['EndpointArn'], is_subscribe)

The rough procedure is

  1. Register endpoint in Application
  2. Subscribe endpoint to Topic

It will be. Please register and acquire the ARN of Application and Topic appearing here using the dashboard on the AWS side in advance.

Register endpoint in Application

handler.py


def add_endpoint(application_arn, token):
    # token(boto3 doc excerpt) :
    # For example, when using APNS as the notification service, you need the device token.
    # Alternatively, when using GCM or ADM, the device token equivalent is called the registration ID.

    client = boto3.client('sns')
    endpoint = client.create_platform_endpoint(
        PlatformApplicationArn=application_arn,
        Token=token
    )

    return endpoint

Call it even if it has already been added. token is a token obtained from APNS or FCM (GCM). create_platform_endpoint () returns the information of the existing endpoint without adding a new one if the endpoint has already been added. In any case, endpoint information can be obtained, so subscribe based on this information.

The CreatePlatformEndpoint action is idempotent, so if the requester already owns an endpoint with the same device token and attributes, that endpoint's ARN is returned without creating a new endpoint.

Subscribe endpoint to Topic

This is a bit of a hassle.

You can simply execute subscribe () to subscribe, but in the case of unsubscribe, SubscriptionArn of the target terminal is required. This time, I execute subscribe () once to get SubscriptionArn, and then use it to execute unsubscribe ().

handler.py


def subscribe_token(topic_arn, endpoint_arn, is_subscribe):

    client = boto3.client('sns')
    subscription = client.subscribe(
        TopicArn=topic_arn,
        Protocol='application',
        Endpoint=endpoint_arn
    )
    if not is_subscribe:
        client.unsubscribe(
            SubscriptionArn=subscription['SubscriptionArn']
        )

Question

This is the last method to get Subscription Arn, but even if you look at the manual, you can only find such a good method. Please point out if there is an appropriate method.

Retest

I got a slightly unclear error at runtime, so I reviewed the boto3 manual and reviewed the code, but I think that it is more straightforward to write as follows. However, rewriting did not improve the error, so I think the client is a low-level client.

handler.py


def add_endpoint(dry_run, application_arn, token):

    sns = boto3.resource('sns')
    platform_application = sns.PlatformApplication(application_arn)
    endpoint = platform_application.create_platform_endpoint(
        Token=token
    )
    return endpoint.arn


def subscribe_token(dry_run, topic_arn, endpoint_arn, is_subscribe):

    sns = boto3.resource('sns')
    topic = sns.Topic(topic_arn)
    subscription = topic.subscribe(
        TopicArn=topic_arn,
        Protocol='application',
        Endpoint=endpoint_arn
    )
    if not is_subscribe:
        subscription.delete()

Recommended Posts

Terminal association from the server side to Amazon SNS (python + boto3)
Push notification from Python server to Android
[Amazon Linux] Switching from Python 2 series to Python 3 series
Try using the Python web framework Django (1)-From installation to server startup
Copy data from Amazon S3 to Google Cloud Storage with Python (boto)
[python] Send the image captured from the webcam to the server and save it
Send a message from Slack to a Python server
How to measure line speed from the terminal
[Python] I will upload the FTP to the FTP server.
[Python] How to remove duplicate values from the list
The wall of changing the Django service from Python 2.7 to Python 3
Changes from Python 3.0 to Python 3.5
Send log data from the server to Splunk Cloud
I wanted to use the Python library from MATLAB
How to instantly launch Jupyter Notebook from the terminal
I raised the Python version from 2 to 3, but every time I restart the ubuntu terminal, the version remains 2.
Query from python to Amazon Athena (using named profile)
ODBC access to SQL Server from Linux with Python
A Python script that allows you to check the status of the server from your browser
[Postgresql] SSH connection to the external DB server from the client
I tried changing the python script from 2.7.11 to 3.6.0 on windows10
Program to determine leap year from the Christian era [Python]
Pass OpenCV data from the original C ++ library to Python
Extract the value closest to a value from a Python list element
Post from Python to Slack
Cheating from PHP to Python
Anaconda updated from 4.2.0 to 4.3.0 (python3.5 updated to python3.6)
I tweeted from the terminal!
Switch from python2.7 to python3.6 (centos7)
Connect to sqlite from python
I made something with python that NOW LOADING moves from left to right on the terminal
An easy way to hit the Amazon Product API in Python
Repeat with While. Scripts to Tweet and search from the terminal
[Cloudian # 9] Try to display the metadata of the object in Python (boto3)
[Python] Try to graph from the image of Ring Fit [OCR]
How to get followers and followers from python using the Mastodon API
Hit the New Relic API in Python to get the server status
From the introduction of JUMAN ++ to morphological analysis of Japanese with Python
[Python + heroku] From the state without Python to displaying something on heroku (Part 2)
Change the active version in Pyenv from anaconda to plain Python
Call Matlab from Python to optimize
Leave the troublesome processing to Python
Create folders from '01' to '12' with python
Post from python to facebook timeline
[Lambda] [Python] Post to Twitter from Lambda!
Existence from the viewpoint of Python
In the python command python points to python3.8
How to get the Python version
[Python] How to import the library
Connect to utf8mb4 database from python
Python (from first time to execution)
Post images from Python to Tumblr
Use the Flickr API from Python
How to access wikipedia from python
Python to switch from another language
Try using Amazon DynamoDB from Python
[Python] Change the alphabet to numbers
Did not change from Python 2 to 3
Update Python on Mac from 2 to 3
Get the width of the div on the server side with Selenium + PhantomJS + Python
I was able to print the thermal printer "PAPERANG" from Python (Windows10, Python3.6)