Cloud + Python
Cloud SDK patterns — storage, serverless handlers, secrets, and deployment helpers.
Generate an Idempotency-Key header mock with UUID in Python
This code provides a mock idempotency service that generates a UUID-based Idempotency-Key header token and validates it, useful for simulating production API behavior in tests.
import uuid
class MockIdempotencyService:
def __init__(self):
self._tokens = {}
def get_token(self, header_name="Idempotency-Key"):
token = str(uuid.uuid4())
self._tokens[header_name] = token
return token
def validate(self, header_name="Idempotency-Key"):
return s…
How to Implement Retry with Exponential Backoff for Cloud API 429 Errors in Python
Implement a retry-with-backoff loop in Python to handle 429 throttling errors from cloud APIs, using exponential delay between attempts.
import time
import random
import requests
def api_call(attempt):
"""Mock cloud API that returns 429 for the first two attempts."""
if attempt < 2:
return 429, "Too Many Requests"
return 200, {"data": "success"}
def retry_with_backoff(api_func, max_retries=3, base_delay=0.1):
for attempt in …
How to Mock AWS Secrets Manager in Python
Create a lightweight mock of AWS Secrets Manager's get_secret_value API to test secret retrieval without cloud dependencies.
import json
from typing import Optional
class MockSecretsManager:
"""A simple mock of AWS Secrets Manager's get_secret_value API."""
def __init__(self):
self._secrets: dict[str, str] = {}
def create_secret(self, secret_id: str, secret_value: str) -> None:
"""Store a secret value under a…
How to Mock Azure Service Bus Queue in Python
A lightweight in-memory mock of the Azure Service Bus queue API for local testing without cloud dependencies.
import json
import time
from collections import deque
class ServiceBusQueueMock:
def __init__(self, queue_name):
self.queue_name = queue_name
self._messages = deque()
self._dead_letter_queue = deque()
self._message_counter = 0
def send_message(self, body, message_id=None, prop…
How to Paginate a List with a Generator in Python
Define a generator that yields list items in fixed-size pages, simulating pagination for cloud resource APIs.
from typing import List, Iterator
def paginate_generator(items: List[str], page_size: int = 3) -> Iterator[List[str]]:
"""Yield items in fixed-size chunks with a mock pagination pattern."""
for i in range(0, len(items), page_size):
yield items[i:i + page_size]
if __name__ == "__main__":
resources…
How to Parse Cloud JSON Data in Python
A helper function that safely parses JSON payloads from cloud services into a clean dict with defaults and error handling.
import json
from typing import Dict, Any
def parse_cloud_data(payload: str) -> Dict[str, Any]:
"""Parse a JSON payload from a cloud service into a clean dict."""
try:
data = json.loads(payload)
return {
"status": data.get("status", "unknown"),
"region": data.get("region…
How to Parse an AWS API Gateway Proxy Event in Python
Extract and parse common fields from a mock API Gateway proxy event, turning the JSON body into a native Python dict.
import json
from typing import Any, Dict, Optional
def parse_proxy_event(event: Dict[str, Any]) -> Dict[str, Any]:
"""Extract and parse common fields from an API Gateway proxy event."""
body = event.get("body", "")
if isinstance(body, str):
body = json.loads(body) if body else {}
elif body is…
Mock SSM Parameter Store Get Parameters by Path in Python
This code implements a simple mock of the AWS SSM Parameter Store get_parameters_by_path API, returning parameters under a given path with recursive and non-recursive options.
import json
class MockSSM:
def __init__(self, parameters):
self.parameters = parameters
def get_parameters_by_path(self, path, recursive=True):
result = []
for key, value in self.parameters.items():
if recursive:
if key.startswith(path):
…
Browse by section
Each section groups closely related Python snippets.
Cloud + Python — Python code examples
What you will find here
This page collects cloud + python snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.