Reference library

Cloud + Python

Cloud SDK patterns — storage, serverless handlers, secrets, and deployment helpers.

10 matches
Cloud + Python medium

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.

url shortener api
Python
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"{…
54 0 Open
Cloud + Python easy

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.

cloud-storage json file-io
Python
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…
15 0 Open
Cloud + Python medium

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.

aws s3 presigned-url
Python
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…
13 0 Open
Cloud + Python easy

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 alert threshold
Python
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…
13 0 Open
Cloud + Python easy

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.

cloud config json
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)
      …
12 0 Open
Cloud + Python easy

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.

aws sts mocking
Python
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",
    …
14 0 Open
Cloud + Python easy

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.

aws tagging compliance
Python
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…
14 0 Open
Cloud + Python medium

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.

aws sqs mock
Python
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 = {
         …
14 0 Open
Cloud + Python easy

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.

cloudfront aws cli
Python
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:
           …
15 0 Open
Cloud + Python easy

Mock ECS Task Run Stop Status Dict in Python

Build a mock ECS task status dictionary with RUNNING/STOPPED states using the standard library.

aws ecs mocking
Python
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…
15 0 Open

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.