|
| 1 | +--- |
| 2 | +title: "Python" |
| 3 | +weight: 1 |
| 4 | +description: Use the LocalStack SDK for Python |
| 5 | +--- |
| 6 | + |
| 7 | +## Introduction |
| 8 | + |
| 9 | +You can use the LocalStack SDK for Python to develop Python applications that interact with the LocalStack platform and internal developer endpoints. |
| 10 | +The SDK extends the REST API, offering an object-oriented interface for easier use. |
| 11 | + |
| 12 | +The LocalStack SDK for Python supports these features: |
| 13 | + |
| 14 | +- Save, list, load, and delete Cloud Pods. |
| 15 | +- Manage fault configurations for the Chaos API. |
| 16 | +- Automatically reset service states. |
| 17 | +- List SQS queue messages without causing side effects. |
| 18 | +- Retrieve and delete sent SES messages. |
| 19 | + |
| 20 | +{{< callout >}} |
| 21 | +This project is still in a preview phase, and will be subject to fast and breaking changes. |
| 22 | +{{< /callout >}} |
| 23 | + |
| 24 | +## Installation |
| 25 | + |
| 26 | +Install the latest `localstack-sdk-python` release via pip: |
| 27 | + |
| 28 | +{{< command >}} |
| 29 | +$ pip install --upgrade localstack-sdk-python |
| 30 | +{{< / command >}} |
| 31 | + |
| 32 | +## Basic Concepts |
| 33 | + |
| 34 | +LocalStack SDK for Python organizes functionality into specific modules like `aws`, `state`, `pods`, and `chaos`. |
| 35 | +For example, the `aws` module allows developers to initialize clients for various AWS services. |
| 36 | +Using the SDK in Python is straightforward: developers can import the relevant modules and initialize specific clients (e.g., `AWSClient`, `StateClient`, `PodsClient`, `ChaosClient`) to perform actions on local AWS services. |
| 37 | + |
| 38 | +### AWS endpoints |
| 39 | + |
| 40 | +#### SQS |
| 41 | + |
| 42 | +The following code snippet shows how to set up an SQS client, create a queue, send messages, and retrieve them to test local SQS interactions using LocalStack. |
| 43 | + |
| 44 | +```python |
| 45 | +import json |
| 46 | +import boto3 |
| 47 | +import localstack.sdk.aws |
| 48 | + |
| 49 | +# Initialize LocalStack AWS client |
| 50 | +client = localstack.sdk.aws.AWSClient() |
| 51 | + |
| 52 | +# Set up SQS client using the LocalStack AWS client configuration |
| 53 | +sqs_client = boto3.client( |
| 54 | + "sqs", |
| 55 | + endpoint_url=client.configuration.host, |
| 56 | + region_name="us-east-1", |
| 57 | + aws_access_key_id="test", |
| 58 | + aws_secret_access_key="test", |
| 59 | +) |
| 60 | + |
| 61 | +# Create an SQS queue |
| 62 | +queue_name = "test-queue" |
| 63 | +sqs_client.create_queue(QueueName=queue_name) |
| 64 | +queue_url = sqs_client.get_queue_url(QueueName=queue_name)["QueueUrl"] |
| 65 | + |
| 66 | +# Send messages to the queue |
| 67 | +for i in range(5): |
| 68 | + sqs_client.send_message( |
| 69 | + QueueUrl=queue_url, |
| 70 | + MessageBody=json.dumps( |
| 71 | + {"event": f"event-{i}", "message": f"message-{i}"} |
| 72 | + ), |
| 73 | + ) |
| 74 | + |
| 75 | +# Retrieve messages from the queue |
| 76 | +response = sqs_client.receive_message( |
| 77 | + QueueUrl=queue_url, |
| 78 | + MaxNumberOfMessages=5 |
| 79 | +) |
| 80 | + |
| 81 | +# Print each message body |
| 82 | +messages = response.get("Messages", []) |
| 83 | +for msg in messages: |
| 84 | + print("Message Body:", msg.get("Body")) |
| 85 | +``` |
| 86 | + |
| 87 | +The following output is displayed: |
| 88 | + |
| 89 | +```bash |
| 90 | +Message Body: {"event": "event-0", "message": "message-0"} |
| 91 | +Message Body: {"event": "event-1", "message": "message-1"} |
| 92 | +Message Body: {"event": "event-2", "message": "message-2"} |
| 93 | +Message Body: {"event": "event-3", "message": "message-3"} |
| 94 | +Message Body: {"event": "event-4", "message": "message-4"} |
| 95 | +``` |
| 96 | + |
| 97 | +#### SES |
| 98 | + |
| 99 | +The following code snippet verifies an email address, sends a raw email, retrieves the message ID, and discards all SES messages afterward. |
| 100 | + |
| 101 | +```python |
| 102 | +import boto3 |
| 103 | +import localstack.sdk.aws |
| 104 | + |
| 105 | +client = localstack.sdk.aws.AWSClient() |
| 106 | + |
| 107 | +# Initialize SES client |
| 108 | +ses_client = boto3.client( |
| 109 | + "ses", |
| 110 | + endpoint_url=client.configuration.host, |
| 111 | + region_name="us-east-1", |
| 112 | + aws_access_key_id="test", |
| 113 | + aws_secret_access_key="test", |
| 114 | +) |
| 115 | + |
| 116 | +# Verify email address |
| 117 | +email = "user@example.com" |
| 118 | +ses_client.verify_email_address(EmailAddress=email) |
| 119 | + |
| 120 | +# Send a raw email |
| 121 | +raw_message_data = f"From: {email}\nTo: recipient@example.com\nSubject: test\n\nThis is the message body.\n\n" |
| 122 | +ses_client.send_raw_email(RawMessage={"Data": raw_message_data}) |
| 123 | + |
| 124 | +# Get and print SES message IDs |
| 125 | +messages = client.get_ses_messages() |
| 126 | +for msg in messages: |
| 127 | + print("Message ID:", msg.id) |
| 128 | + |
| 129 | +# Discard all SES messages |
| 130 | +client.discard_ses_messages() |
| 131 | +``` |
| 132 | + |
| 133 | +The following output is displayed: |
| 134 | + |
| 135 | +```bash |
| 136 | +Message ID: khqzljuixhpnpejl-mnlhgajk-ebch-zfxq-orit-qgexxjlrkipo-ywgvwr |
| 137 | +``` |
| 138 | + |
| 139 | +### State Management |
| 140 | + |
| 141 | +LocalStack provides various features for managing local state, including Cloud Pods, which allow for saving, loading, and deleting cloud states. |
| 142 | + |
| 143 | +### Cloud Pods |
| 144 | + |
| 145 | +Cloud Pods is a feature that enables storing and managing snapshots of the current state. |
| 146 | +This code snippet shows listing available pods, saving a new pod, loading it, and then deleting it. |
| 147 | +You need to set your `LOCALSTACK_AUTH_TOKEN` in your terminal session before running the snippet. |
| 148 | + |
| 149 | +```python |
| 150 | +from localstack.sdk.pods import PodsClient |
| 151 | + |
| 152 | +POD_NAME = "ls-cloud-pod" |
| 153 | +client = PodsClient() |
| 154 | + |
| 155 | +# List all pods |
| 156 | +pods = client.list_pods() |
| 157 | +print("Pods:", pods) |
| 158 | + |
| 159 | +# Save Cloud Pod |
| 160 | +client.save_pod(pod_name=POD_NAME) |
| 161 | +print(f"Pod '{POD_NAME}' saved.") |
| 162 | + |
| 163 | +# Load Cloud Pod |
| 164 | +client.load_pod(pod_name=POD_NAME) |
| 165 | +print(f"Pod '{POD_NAME}' loaded.") |
| 166 | + |
| 167 | +# Delete Cloud Pod |
| 168 | +client.delete_pod(pod_name=POD_NAME) |
| 169 | +print(f"Pod '{POD_NAME}' deleted.") |
| 170 | +``` |
| 171 | + |
| 172 | +The following output is displayed: |
| 173 | + |
| 174 | +```bash |
| 175 | +Pods: cloudpods=[PodListCloudpodsInner(max_version=1, pod_name='check-pod', last_change=None)] |
| 176 | +Pod 'ls-cloud-pod' saved. |
| 177 | +Pod 'ls-cloud-pod' loaded. |
| 178 | +Pod 'ls-cloud-pod' deleted. |
| 179 | +``` |
| 180 | + |
| 181 | +### State Reset |
| 182 | + |
| 183 | +The following example demonstrates how to reset the current cloud state using LocalStack’s `StateClient`. |
| 184 | + |
| 185 | +```python |
| 186 | +import boto3 |
| 187 | +from localstack.sdk.state import StateClient |
| 188 | + |
| 189 | +# Initialize StateClient and SQS client |
| 190 | +client = StateClient() |
| 191 | +sqs_client = boto3.client( |
| 192 | + "sqs", |
| 193 | + endpoint_url=client.configuration.host, |
| 194 | + region_name="us-east-1", |
| 195 | + aws_access_key_id="test", |
| 196 | + aws_secret_access_key="test", |
| 197 | +) |
| 198 | + |
| 199 | +# Create SQS queue |
| 200 | +sqs_client.create_queue(QueueName="test-queue") |
| 201 | +url = sqs_client.get_queue_url(QueueName="test-queue")["QueueUrl"] |
| 202 | +print("Queue URL before reset:", url) |
| 203 | + |
| 204 | +# Reset state |
| 205 | +client.reset_state() |
| 206 | +print("State reset.") |
| 207 | + |
| 208 | +# Try to retrieve the queue URL after state reset |
| 209 | +try: |
| 210 | + sqs_client.get_queue_url(QueueName="test-queue") |
| 211 | +except Exception as exc: |
| 212 | + error_code = exc.response["Error"]["Code"] |
| 213 | + print("Error after state reset:", error_code) |
| 214 | +``` |
| 215 | + |
| 216 | +The following output is displayed: |
| 217 | + |
| 218 | +```bash |
| 219 | +Queue URL before reset: http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/test-queue |
| 220 | +State reset. |
| 221 | +Error after state reset: AWS.SimpleQueueService.NonExistentQueue |
| 222 | +``` |
| 223 | + |
| 224 | +### Chaos API |
| 225 | + |
| 226 | +LocalStack’s Chaos API enables fault injection to simulate issues in AWS services. |
| 227 | +This example shows how to add a fault rule for the S3 service, retrieve and display the rule, and finally delete it to return to normal operations. |
| 228 | + |
| 229 | +```python |
| 230 | +import localstack.sdk.chaos |
| 231 | +from localstack.sdk.models import FaultRule |
| 232 | + |
| 233 | +# Initialize ChaosClient |
| 234 | +client = localstack.sdk.chaos.ChaosClient() |
| 235 | + |
| 236 | +# Add a fault rule for S3 |
| 237 | +rule = FaultRule(region="us-east-1", service="s3") |
| 238 | +rules = client.add_fault_rules(fault_rules=[rule]) |
| 239 | +print("Added S3 rule:", [(r.region, r.service) for r in rules]) |
| 240 | + |
| 241 | +# Retrieve and display current fault rules |
| 242 | +rules = client.get_fault_rules() |
| 243 | +print("Current rules:", [(r.region, r.service) for r in rules]) |
| 244 | + |
| 245 | +# Delete the S3 fault rule |
| 246 | +rules = client.delete_fault_rules(fault_rules=[rule]) |
| 247 | +print("Rules after deleting S3 rule:", [(r.region, r.service) for r in rules]) |
| 248 | +``` |
| 249 | + |
| 250 | +The following output is displayed: |
| 251 | + |
| 252 | +```bash |
| 253 | +Added S3 rule: [('us-east-1', 's3')] |
| 254 | +Current rules: [('us-east-1', 's3')] |
| 255 | +Rules after deleting S3 rule: [] |
| 256 | +``` |
0 commit comments