14
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AWS SDK で SQS を Python で操作する

Last updated at Posted at 2018-01-11

今回はPythonのAWS SDKでSQSメッセージの送受信を行います.

#前提

  • aws cli の configure を済ませている

#ソースコード
設定はconfigparserモジュールを使用します.

config.ini
[sqs]
url : https://sqs.ap-northeast-1.amazonaws.com/YYYYYYY/XXX

それではソースコードです.

sqs.py
# -*- coding: utf-8 -*-

import configparser
import boto3
import json

# configファイルの読み込み
ini = configparser.SafeConfigParser()
ini.read("./config.ini")

sqs = boto3.client('sqs')
url = ini.get("sqs", "url")

# 送信するJSON
body = {"type": "Right", "Action": "On"}

# SQSへJSONの送信
response = sqs.send_message(
    QueueUrl=url,
    DelaySeconds=0,
    MessageBody=(
        json.dumps(body)
    )
)

# SQSからJSONを受信
response = sqs.receive_message(
    QueueUrl=url,
    AttributeNames=[
        'SentTimestamp'
    ],
    MaxNumberOfMessages=1,
    VisibilityTimeout=0,
    WaitTimeSeconds=0
)

message = response['Messages'][0]
body = json.loads(message['Body'])
print(body)

# メッセージを削除するための情報を取得
receipt_handle = message['ReceiptHandle']

# メッセージを削除
sqs.delete_message(
    QueueUrl=url,
    ReceiptHandle=receipt_handle
)

実行します.

$python3 sqs.py
{'Action': 'On', 'type': 'Right'}

無事JSONを受信できました.
Alexaを使って遊ぼうと考えているので今日はその準備にSQSを使用してみました.

#参考文献

14
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?