Example of using Yandex Message Queue in Python
Written by
Updated at October 25, 2024
Warning
To work with Yandex Message Queue from Python, use boto3
Installing
To install boto, follow the instructions in the developer's repository: boto3
Getting started
- Create a service account.
- Assign the editor role to the service account.
- Create a static access key.
Set the environment variables:
export AWS_ACCESS_KEY_ID="<access_key_ID>"
export AWS_SECRET_ACCESS_KEY="<secret_key>"
Example
In this example:
- A connection with Message Queue is established.
- A queue named
mq_example_boto3
is created. - A message with the text
boto3 sample message
is sent to the queue. - The message is read from the queue and displayed in the terminal.
- The received message is removed from the queue.
- The message queue is deleted.
import boto3
def main():
# Create client
client = boto3.client(
service_name='sqs',
endpoint_url='https://message-queue.api.cloud.yandex.net',
region_name='ru-central1'
)
# Create queue and get its url
queue_url = client.create_queue(QueueName='mq_example_boto3').get('QueueUrl')
print('Created queue url is "{}"'.format(queue_url))
# Send message to queue
client.send_message(
QueueUrl=queue_url,
MessageBody='boto3 sample message'
)
print('Successfully sent test message to queue')
# Receive sent message
messages = client.receive_message(
QueueUrl=queue_url,
MaxNumberOfMessages=10,
VisibilityTimeout=60,
WaitTimeSeconds=20
).get('Messages')
for msg in messages:
print('Received message: "{}"'.format(msg.get('Body')))
# Delete processed messages
for msg in messages:
client.delete_message(
QueueUrl=queue_url,
ReceiptHandle=msg.get('ReceiptHandle')
)
print('Successfully deleted message by receipt handle "{}"'.format(msg.get('ReceiptHandle')))
# Delete queue
client.delete_queue(QueueUrl=queue_url)
print('Successfully deleted queue')
if __name__ == '__main__':
main()