2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Python] SQS拡張クライアントライブラリ

Last updated at Posted at 2024-10-26

SQS拡張クライアントライブラリ

SQSのペイロード256KB制限を超えたいときに利用できる拡張ライブラリ、最近Pythonでもライブラリが公開された。

S3を経由してメッセージを伝えているが、それらを隠蔽しているだけなので自作したほうがいいかもしれない

公式のチュートリアル

import boto3
import sqs_extended_client

sqs_extended_client = boto3.client("sqs", region_name="us-east-1")
sqs_extended_client.large_payload_support = "S3_BUCKET_NAME" 
sqs_extended_client.use_legacy_attribute = False


これでもいいが、分かりにくいのとLinterに引っかかるためboto3.Sessionクラスを継承したSQSExtendedClientSessionを使うほうが好き。

from sqs_extended_client.client import SQSExtendedClientSession

client = SQSExtendedClientSession().client("sqs")

client.large_payload_support = "<BUCKET_NAME>"
client.use_legacy_attribute = False

#送信
send_message_response = client.send_message(
    QueueUrl="<QUEUE_URL>",
    MessageBody=large_message
)
assert send_message_response['ResponseMetadata']['HTTPStatusCode'] == 200
#受信
receive_message_response = client.receive_message(
    QueueUrl="<QUEUE_URL>",
    MessageAttributeNames=['All']
)

Lambdaでポーリングしている場合は以下のようにしてメッセージを取得している

from aws_lambda_powertools.utilities.batch import (
    BatchProcessor,
    EventType,
    process_partial_response,
)
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
from sqs_extended_client import SQSExtendedClientSession

processor = BatchProcessor(event_type=EventType.SQS)

client = SQSExtendedClientSession().client("sqs", region_name="ap-northeast-1")
client.large_payload_support = "<BUCKET_NAME>"
client.use_legacy_attribute = False
client.delete_payload_from_s3 = True 

def record_handler(record: SQSRecord) -> str:
    body = sqs_extend_client.retrieve_message_from_s3(record.body)
    
    #
    
def lambda_handler(event, context: LambdaContext):
    return process_partial_response(
        event=event,
        record_handler=record_handler,
        processor=processor,
        context=context,
    )


インストールするときの名前はamazon-sqs-extended-clientです

pip install sqs-extended-clientとすると開発が止まってしまった、よく似たライブラリがインストールされるので注意

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?