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…
Create a Data Helper Class for Beginners in Python
A simple Python class to read and write JSON and CSV files from a local directory, ideal for automating data workflows in cloud environments.
import json
from pathlib import Path
class DataHelper:
"""Simple helper for reading and writing common data files."""
def __init__(self, directory="data"):
self.directory = Path(directory)
self.directory.mkdir(exist_ok=True)
def save_json(self, filename, data):
filepath =…
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.""…
Exponential Backoff with Jitter for Cloud API Calls in Python
A Python snippet demonstrating exponential backoff with jitter for retrying transient cloud API failures, using a simulated client that has a configurable success rate.
import random
import time
def exponential_backoff_with_jitter(retries=5, base_delay=0.5, max_delay=4.0, jitter_factor=0.3):
for attempt in range(1, retries + 1):
delay = min(max_delay, base_delay * (2 ** (attempt - 1)))
jitter = delay * random.uniform(-jitter_factor, jitter_factor)
effect…
Generate Mock CloudFormation Stack Events in Python
Generate a list of mock AWS CloudFormation stack events with random resources, statuses, and timestamps, and print them as JSON.
import json
import random
from datetime import datetime, timedelta
def generate_mock_stack_events(stack_name="MyTestStack", num_events=10):
"""Generate a list of mock CloudFormation stack events."""
resources = [
("AWS::S3::Bucket", "MyBucket"),
("AWS::EC2::Instance", "MyInstance"),
("…
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…
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 Calculate VPC Subnet CIDR Details in Python
Compute network address, broadcast address, address count, prefix length, and netmask for any IPv4 CIDR using the Python standard library's ipaddress module.
import ipaddress
def subnet_details(cidr: str) -> dict:
network = ipaddress.ip_network(cidr, strict=False)
return {
"network_address": str(network.network_address),
"broadcast_address": str(network.broadcast_address),
"num_addresses": network.num_addresses,
"prefix_length": ne…
How to Convert Python Dict to JSON and Back
Convert Python dictionaries to JSON text and back with a simple helper that serializes and deserializes data structures.
import json
from datetime import datetime, timezone
def convert_data(data, source_format=None, target_format="json"):
"""
Convert Python data structures to txt/json and back.
For beginners: shows how to serialize/deserialize.
"""
if source_format == "json" and target_format == "dict":
ret…
How to Create a JSON Data Helper in Python
A beginner-friendly DataHelper class that safely reads and writes JSON files with timestamps to a local data directory.
from datetime import datetime
from pathlib import Path
import json
class DataHelper:
"""Simple helper for reading/writing JSON files safely."""
def __init__(self, base_dir="data"):
self.base_dir = Path(base_dir)
self.base_dir.mkdir(exist_ok=True)
def save(self, filename, data):
…
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 Design a Cloud Data Helper Class in Python
A beginner-friendly Python helper class that saves, loads, and aggregates JSON records locally, simulating cloud-style data handling.
import json
from pathlib import Path
from datetime import datetime
class CloudDataHelper:
"""Beginner-friendly helper for working with cloud-based JSON data."""
def __init__(self, base_dir="cloud_data"):
self.base_dir = Path(base_dir)
self.base_dir.mkdir(exist_ok=True)
def save_record(s…
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 Evaluate Mock NACL Rules in Python
Simulate numbered AWS Network ACL rule evaluation with HMAC integrity checks on request payloads.
import base64
import json
import hmac
import hashlib
def evaluate_mock_rule(rule_number, request_data, secret):
"""
Simulates evaluating an NACL-like numbered rule by:
1. Checking if the rule number exists in the mock policy.
2. Computing an HMAC over the request payload for integrity.
"""
# M…
How to Implement Region Failover Config in Python with Primary and Secondary Mock
This Python class simulates regional failover: it tracks active region, switches to secondary on primary failure, and allows manual recovery.
import time
class RegionFailoverConfig:
def __init__(self, primary, secondary):
self.primary = primary
self.secondary = secondary
self.active = primary
self.failover_count = 0
self.healthy = True
def check_health(self):
"""Mock health check - returns True if ac…
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 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 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 Key Vault Secret Get in Python
Mock an Azure Key Vault client's get_secret method with unittest.mock to test functions that retrieve secret values without hitting the real service.
import unittest
from unittest.mock import MagicMock, patch
def get_secret(key_vault_client, secret_name):
"""Retrieve a secret value from an Azure Key Vault client."""
secret = key_vault_client.get_secret(secret_name)
return secret.value
class TestKeyVaultSecretGet(unittest.TestCase):
def test_get_…
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 Mock DynamoDB with a Simple Dict Store in Python
A lightweight in-memory DynamoDB mock that stores items in a dict and supports put, get, and query-by-value operations for local testing.
import json
from typing import Any, Dict, Optional
class MockDynamoDB:
def __init__(self) -> None:
self._store: Dict[str, Dict[str, Any]] = {}
def put_item(self, table_name: str, item: Dict[str, Any]) -> None:
key = str(item.get("id"))
if table_name not in self._store:
se…
How to Mock GCP Cloud Functions HTTP Events in Python
Simulate a GCP Cloud Functions HTTP event with a Python mock handler that constructs a realistic event payload and returns a JSON response.
import json
from datetime import datetime, timezone
def mock_http_event(data):
"""Simulate a GCP Cloud Function HTTP event."""
event = {
"event_id": "mock-event-12345",
"timestamp": datetime.now(timezone.utc).isoformat(),
"event_type": "google.cloud.functions.http",
"resource"…
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.