Skip to content

Instantly share code, notes, and snippets.

@enzzc
Created June 30, 2019 14:40
Show Gist options
  • Save enzzc/b3cbc4668fe791c2df96ea69a899c1cb to your computer and use it in GitHub Desktop.
Save enzzc/b3cbc4668fe791c2df96ea69a899c1cb to your computer and use it in GitHub Desktop.
Simple example using AWS SQS with aiobotocore
import pathlib
import json
import asyncio
import aiobotocore
import time
import uuid
def message(msg):
return json.dumps({
'ts': int(time.time()),
'idem': str(uuid.uuid4()),
'msg': msg,
})
with open(pathlib.Path.cwd() / 'secret.json') as f:
secrets = json.load(f)
ACCESS_ID_KEY = secrets['access_id_key']
SECRET_ACCESS_KEY = secrets['secret_access_key']
REGION = 'ap-northeast-1' # Tokyo
async def main():
session = aiobotocore.get_session()
client = session.create_client(
'sqs',
region_name=REGION,
aws_secret_access_key=SECRET_ACCESS_KEY,
aws_access_key_id=ACCESS_ID_KEY
)
resp = await client.get_queue_url(QueueName='testq')
qurl = resp['QueueUrl']
# PRODUCE
await client.send_message(
QueueUrl=qurl,
MessageBody=message('hello')
)
# CONSUME
while True:
msgs = await client.receive_message(
QueueUrl=qurl,
WaitTimeSeconds=2
)
if 'Messages' in msgs:
for msg in msgs['Messages']:
print(msg['Body'])
await client.delete_message(
QueueUrl=qurl,
ReceiptHandle=msg['ReceiptHandle']
)
else:
print('Empty queue!')
break
await client.close()
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment