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"{…
Create a Cloud Storage Helper Class in Python
Build a simple local file-based helper class that mimics cloud storage operations like save, load, and list JSON objects.
import datetime
import json
from pathlib import Path
class CloudDataHelper:
"""Simple helper for reading/writing JSON files in a cloud-style folder."""
def __init__(self, base_dir: str = "cloud_storage"):
self.base_dir = Path(base_dir)
self.base_dir.mkdir(exist_ok=True)
def save_json(se…
Generate a Mock Presigned URL in Python with HMAC
Build a mock AWS S3 presigned URL using an HMAC-SHA256 signature, mimicking the core SigV4 pattern without cloud SDK dependencies.
import hashlib
import hmac
import time
import base64
def generate_presigned_url_mock(secret_key, bucket, object_key, expires_in=3600):
# Build the canonical request string (simplified AWS SigV4 style)
timestamp = str(int(time.time()))
expiry = str(int(time.time()) + expires_in)
payload = f"GET\n/{buck…
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 Build a Budget Alert Threshold with Mock Notifications in Python
This code calculates budget usage percentage and triggers a mock alert notification when the usage exceeds a defined threshold.
budget = 500.0
spent = 620.0
alert_threshold = 0.8
def mock_notify(percent_used):
if percent_used >= alert_threshold:
return f"ALERT: Budget usage at {percent_used * 100:.1f}% — over {alert_threshold * 100:.0f}% threshold!"
return f"OK: Budget usage at {percent_used * 100:.1f}% — under threshold."
pe…
How to Build a Multi-Cloud Config Loader with Provider Switching in Python
Load cloud provider configurations (AWS, Azure, GCP) from JSON files using a provider dispatch pattern in Python.
import json
from pathlib import Path
from dataclasses import dataclass
from typing import Dict, Any
@dataclass
class CloudConfig:
provider: str
region: str
settings: Dict[str, Any]
class ConfigLoader:
def __init__(self, config_dir: str = "configs"):
self.config_dir = Path(config_dir)
…
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 Enforce Tag Policies on AWS Resources in Python
Build a reusable Python class that checks AWS resources against a required-tag policy and reports compliance with missing tags.
import json
from dataclasses import dataclass, field
from typing import Dict, List
@dataclass
class Resource:
arn: str
tags: Dict[str, str] = field(default_factory=dict)
class TagPolicyEnforcer:
def __init__(self, required_tags: List[str]):
self.required_tags = set(required_tags)
def enfor…
How to Mock AWS SQS Send Receive Delete in Python
Build an in-memory mock of the SQS send, receive, and delete message flow for local testing.
import json
from collections import deque
from uuid import uuid4
class MockSQSQueue:
def __init__(self, name):
self.name = name
self._messages = deque()
self._in_flight = {}
def send_message(self, body, attributes=None):
message_id = str(uuid4())
message = {
…
How to Mock CloudFront Invalidation Paths in Python
Build a sorted, deduplicated list of CloudFront invalidation paths from a set of file paths, adding implicit index.html entries.
import argparse
def build_invalidation_paths(files, include_index=True):
"""
Create CloudFront invalidation paths from a list of files.
Converts file names to root-relative paths and optionally adds /index.html.
"""
paths = []
for f in files:
f = f.strip()
if not f:
…
How to Validate Data Fields and Types in Python
Validate required fields and type correctness in a Python dictionary with small helper functions, returning a list of clear error messages.
import json
from typing import Any, Dict, List
def validate_data(data: Dict[str, Any], required_fields: List[str]) -> List[str]:
"""Check required fields exist and are non-empty. Return list of errors."""
errors = []
for field in required_fields:
value = data.get(field)
if value is None o…
Mock ECS Task Run Stop Status Dict in Python
Build a mock ECS task status dictionary with RUNNING/STOPPED states using the standard library.
from datetime import datetime, timezone
def mock_ecs_task_status(task_id: str, state: str = "RUNNING") -> dict:
"""Return a mock ECS task status dictionary."""
return {
"taskArn": f"arn:aws:ecs:us-east-1:123456789012:task/cluster/{task_id}",
"taskDefinition": "arn:aws:ecs:us-east-1:1234567890…
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.