Cloud + Python
Cloud SDK patterns — storage, serverless handlers, secrets, and deployment helpers.
Build a URL Shortener Client with Python
A Python class that shortens long URLs and resolves short codes using a REST API built with requests.
import json
import sys
import requests
class URLShortenerClient:
def __init__(self, base_url="http://tinyurl.com"):
self.base_url = base_url
def shorten_url(self, long_url):
payload = {"url": long_url}
headers = {"Content-Type": "application/json"}
response = requests.post(f"{…
Cross Account Role Chaining Mock Credentials in Python
Simulate AWS STS AssumeRole with mock credentials for cross-account role chaining in Python.
import json
class CredentialChain:
def __init__(self, account_id, role_name):
self.account_id = account_id
self.role_name = role_name
self.credentials = {}
def assume_role(self, session_name="mock_session"):
"""Simulate STS AssumeRole, returning mock credentials with expiry.""…
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 Create a Mock STS AssumeRole Credentials Dict in Python
Build a realistic AWS STS AssumeRole response dict with temporary credentials, expiry time, and assumed role ARN for local testing.
import json
from datetime import datetime, timedelta, timezone
def mock_sts_credentials(role_arn, session_name, duration=3600):
now = datetime.now(timezone.utc)
expiration = now + timedelta(seconds=duration)
credentials = {
"Credentials": {
"AccessKeyId": "ASIAEXAMPLEACCESSKEY",
…
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 RDS Snapshot Create and Restore in Python
Mock AWS RDS snapshot creation and restore operations in Python tests using moto and boto3 without hitting real AWS services.
import boto3
from moto import mock_rds
@mock_rds
def create_and_restore_snapshot():
client = boto3.client("rds", region_name="us-east-1")
client.create_db_instance(
DBInstanceIdentifier="my-db",
DBInstanceClass="db.t3.micro",
Engine="postgres",
AllocatedStorage=20,
Mas…
How to mock boto3 S3 upload in Python
Shows how to mock the boto3 S3 client with unit tests and wrap an upload function to return a dictionary with status details.
import boto3
from unittest.mock import Mock, patch
class S3Uploader:
def __init__(self, bucket_name):
self.bucket_name = bucket_name
self.s3 = boto3.client("s3", region_name="us-east-1")
def upload_file(self, local_path, s3_key):
self.s3.upload_file(local_path, self.bucket_name, s3_ke…
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.