Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
Add cloudflare-python-workers skill
Jezacf1b932e530
diff --git a/skills/cloudflare-python-workers/.claude-plugin/plugin.json b/skills/cloudflare-python-workers/.claude-plugin/plugin.jsonnew file mode 100644index 00000000..6c722e44--- /dev/null+++ b/skills/cloudflare-python-workers/.claude-plugin/plugin.json@@ -0,0 +1,12 @@+{+ "name": "cloudflare-python-workers",+ "description": "Build Python APIs on Cloudflare Workers using pywrangler CLI and WorkerEntrypoint class pattern. Includes Python Workflows for multi-step DAG automation with @step.do decorators. Use when: building Python serverless APIs, migrating Python code to edge, using Python ML libraries, or creating durable workflows. Prevents async errors, package compatibility issues, handler pattern mistakes. async def fetch(self, request): return Response(Hello from Python Worker!) name: my-python-worker, main: src/e",+ "version": "1.0.0",+ "author": {+ "name": "Jeremy Dawes",+ "email": "[email protected]"+ },+ "license": "MIT",+ "repository": "https://github.com/jezweb/claude-skills",+ "keywords": []+}diff --git a/skills/cloudflare-python-workers/README.md b/skills/cloudflare-python-workers/README.mdnew file mode 100644index 00000000..c010c5ce--- /dev/null+++ b/skills/cloudflare-python-workers/README.md@@ -0,0 +1,125 @@+# Cloudflare Python Workers++**Status**: Beta+**Last Updated**: 2025-12-08++## Auto-Trigger Keywords++Claude automatically uses this skill when you mention:++### Primary Technologies+- Python Workers+- Cloudflare Python+- pywrangler+- workers-py+- Python serverless+- Python edge computing+- WorkerEntrypoint+- Python on Cloudflare++### Secondary Keywords+- pyproject.toml workers+- uv pywrangler+- Pyodide+- Python async workers+- Python Workflows+- DAG workflows Python+- step.do decorator++### Error-Based Keywords+- "python_workers compatibility flag"+- "WorkerEntrypoint not found"+- "Package not found in Pyodide"+- "cannot use blocking call in async context"+- "on_fetch is not defined"+- "No module named" (Python Worker context)+- "python_workflows"++### Framework Keywords+- FastAPI Workers+- httpx Cloudflare+- aiohttp Workers+- Python FFI Cloudflare++---++## What This Skill Does++- Sets up Python Worker projects with pywrangler CLI+- Implements WorkerEntrypoint class pattern (current standard)+- Configures Python Workflows with @step.do decorators+- Accesses Cloudflare bindings (D1, KV, R2, AI) from Python+- Uses FFI for JavaScript interop+- Handles async HTTP with httpx/aiohttp+- Prevents 8 common Python Worker errors++---++## Known Issues Prevented++| Issue | Error | Prevention |+|-------|-------|------------|+| Legacy handlers | `on_fetch is not defined` | Use WorkerEntrypoint class |+| Sync HTTP | `blocking call in async context` | Use httpx/aiohttp |+| Native packages | `ModuleNotFoundError` | Pure Python only |+| Missing flags | `python_workers required` | Add compatibility flag |+| Workflow I/O | State not persisted | I/O inside steps |+| Serialization | `not JSON serializable` | JSON-safe returns |+| Cold starts | High latency | Lazy imports |+| Package install | Install failures | Check Pyodide compat |++---++## Token Efficiency++| Scenario | Without Skill | With Skill | Savings |+|----------|---------------|------------|---------|+| Setup Python Worker | ~12k tokens | ~4k tokens | ~67% |+| Create Workflow | ~10k tokens | ~4k tokens | ~60% |+| Debug handler error | ~6k tokens | ~2k tokens | ~67% |++---++## When to Use This Skill++### Use When+- Building Python APIs on Cloudflare Workers+- Migrating existing Python code to edge+- Using Python ML/data libraries (Pyodide-compatible)+- Creating durable multi-step workflows in Python+- Need Python-specific patterns for Cloudflare++### Don't Use When+- Building JavaScript/TypeScript Workers (use cloudflare-worker-base)+- Need lowest possible cold starts (use JavaScript)+- Require native/compiled packages (not supported)+- Building Pages sites (use Workers with Static Assets)++---++## Latest Versions (Dec 2025)++| Package | Version |+|---------|---------|+| workers-py | latest |+| workers-runtime-sdk | latest |+| wrangler | ^4.0.0 |+| Python | 3.12+ |++---++## Official Documentation++- [Python Workers Overview](https://developers.cloudflare.com/workers/languages/python/)+- [Pywrangler CLI](https://github.com/cloudflare/workers-py)+- [Python Workflows](https://developers.cloudflare.com/workflows/python/)+- [Pyodide Packages](https://pyodide.org/en/stable/usage/packages-in-pyodide.html)++---++## Related Skills++- `cloudflare-worker-base` - JavaScript Worker foundation+- `cloudflare-workflows` - JavaScript Workflows+- `cloudflare-d1` - D1 database patterns+- `fastapi` - FastAPI framework patternsdiff --git a/skills/cloudflare-python-workers/SKILL.md b/skills/cloudflare-python-workers/SKILL.mdnew file mode 100644index 00000000..cebeab7a--- /dev/null+++ b/skills/cloudflare-python-workers/SKILL.md@@ -0,0 +1,559 @@+---+name: cloudflare-python-workers+description: |+ Build Python APIs on Cloudflare Workers using pywrangler CLI and WorkerEntrypoint class pattern.+ Includes Python Workflows for multi-step DAG automation with @step.do decorators.++ Use when: building Python serverless APIs, migrating Python code to edge, using Python ML libraries,+ or creating durable workflows. Prevents async errors, package compatibility issues, handler pattern mistakes.+---++# Cloudflare Python Workers++**Status**: Beta (requires `python_workers` compatibility flag)+**Runtime**: Pyodide (Python 3.12+ compiled to WebAssembly)+**CLI**: pywrangler (Dec 2025)+**Last Verified**: 2025-12-08++## Quick Start (5 Minutes)++### 1. Prerequisites++Ensure you have installed:+- [uv](https://docs.astral.sh/uv/#installation) - Python package manager+- [Node.js](https://nodejs.org/) - Required for Wrangler++### 2. Initialize Project++```bash+# Create project directory+mkdir my-python-worker && cd my-python-worker++# Initialize Python project+uv init++# Install pywrangler+uv tool install workers-py++# Initialize Worker configuration+uv run pywrangler init+```++### 3. Create Entry Point++Create `src/entry.py`:++```python+from workers import WorkerEntrypoint, Response++class Default(WorkerEntrypoint):+ async def fetch(self, request):+ return Response("Hello from Python Worker!")+```++### 4. Configure wrangler.jsonc++```jsonc+{+ "name": "my-python-worker",+ "main": "src/entry.py",+ "compatibility_date": "2025-12-01",+ "compatibility_flags": ["python_workers"]+}+```++### 5. Run Locally++```bash+uv run pywrangler dev+# Visit http://localhost:8787+```++### 6. Deploy++```bash+uv run pywrangler deploy+```++---++## Core Concepts++### WorkerEntrypoint Class Pattern++As of August 2025, Python Workers use a class-based pattern (not global handlers):++```python+from workers import WorkerEntrypoint, Response++class Default(WorkerEntrypoint):+ async def fetch(self, request):+ # Access bindings via self.env+ value = await self.env.MY_KV.get("key")++ # Parse request+ url = request.url+ method = request.method++ return Response(f"Method: {method}, URL: {url}")+```++### Accessing Bindings++All Cloudflare bindings are accessed via `self.env`:++```python+class Default(WorkerEntrypoint):+ async def fetch(self, request):+ # D1 Database+ result = await self.env.DB.prepare("SELECT * FROM users").all()++ # KV Storage+ value = await self.env.MY_KV.get("key")+ await self.env.MY_KV.put("key", "value")++ # R2 Object Storage+ obj = await self.env.MY_BUCKET.get("file.txt")++ # Workers AI+ response = await self.env.AI.run("@cf/meta/llama-2-7b-chat-int8", {+ "prompt": "Hello!"+ })++ return Response("OK")+```++**Supported Bindings**:+- D1 (SQL database)+- KV (key-value storage)+- R2 (object storage)+- Workers AI+- Vectorize+- Durable Objects+- Queues+- Analytics Engine++See [Cloudflare Bindings Documentation](https://developers.cloudflare.com/workers/runtime-apis/bindings/) for details.++### Request/Response Handling++```python+from workers import WorkerEntrypoint, Response+import json++class Default(WorkerEntrypoint):+ async def fetch(self, request):+ # Parse JSON body+ if request.method == "POST":+ body = await request.json()+ return Response(+ json.dumps({"received": body}),+ headers={"Content-Type": "application/json"}+ )++ # Query parameters+ url = URL(request.url)+ name = url.searchParams.get("name", "World")++ return Response(f"Hello, {name}!")+```++### Scheduled Handlers (Cron)++```python+from workers import handler++@handler+async def on_scheduled(event, env, ctx):+ # Run on cron schedule+ print(f"Cron triggered at {event.scheduledTime}")++ # Do work...+ await env.MY_KV.put("last_run", str(event.scheduledTime))+```++Configure in wrangler.jsonc:++```jsonc+{+ "triggers": {+ "crons": ["*/5 * * * *"] // Every 5 minutes+ }+}+```++---++## Python Workflows++Python Workflows enable durable, multi-step automation with automatic retries and state persistence.++### Basic Workflow++```python+from workers import WorkflowEntrypoint, WorkerEntrypoint, Response++class MyWorkflow(WorkflowEntrypoint):+ async def run(self, event, step):+ # Step 1+ @step.do("fetch data")+ async def fetch_data():+ response = await fetch("https://api.example.com/data")+ return await response.json()++ data = await fetch_data()++ # Step 2: Sleep+ await step.sleep("wait", "10 seconds")++ # Step 3: Process+ @step.do("process data")+ async def process_data():+ return {"processed": True, "count": len(data)}++ result = await process_data()+ return result+++class Default(WorkerEntrypoint):+ async def fetch(self, request):+ # Create workflow instance+ instance = await self.env.MY_WORKFLOW.create()+ return Response(f"Workflow started: {instance.id}")+```++### DAG Dependencies++Define step dependencies for parallel execution:++```python+class MyWorkflow(WorkflowEntrypoint):+ async def run(self, event, step):+ @step.do("step_a")+ async def step_a():+ return "A done"++ @step.do("step_b")+ async def step_b():+ return "B done"++ # step_c waits for both step_a and step_b+ @step.do("step_c", depends=[step_a, step_b], concurrent=True)+ async def step_c(result_a, result_b):+ return f"C received: {result_a}, {result_b}"++ return await step_c()+```++### Workflow Configuration++```jsonc+{+ "compatibility_flags": ["python_workers", "python_workflows"],+ "compatibility_date": "2025-08-01",+ "workflows": [+ {+ "name": "my-workflow",+ "binding": "MY_WORKFLOW",+ "class_name": "MyWorkflow"+ }+ ]+}+```++---++## Package Management++### pyproject.toml Configuration++```toml+[project]+name = "my-python-worker"+version = "0.1.0"+requires-python = ">=3.12"+dependencies = [+ "beautifulsoup4",+ "httpx"+]++[dependency-groups]+dev = [+ "workers-py",+ "workers-runtime-sdk"+]+```++### Supported Packages++Python Workers support:+- **Pure Python packages** from PyPI+- **Pyodide packages** (pre-built for WebAssembly)++See [Pyodide packages list](https://pyodide.org/en/stable/usage/packages-in-pyodide.html).++### HTTP Clients++Only **async** HTTP libraries work:++```python+# ✅ WORKS - httpx (async)+import httpx++async with httpx.AsyncClient() as client:+ response = await client.get("https://api.example.com")++# ✅ WORKS - aiohttp+import aiohttp++async with aiohttp.ClientSession() as session:+ async with session.get("https://api.example.com") as response:+ data = await response.json()++# ❌ DOES NOT WORK - requests (sync)+import requests # Will fail!+```++### Requesting New Packages++Request support for new packages at:+https://github.com/cloudflare/workerd/discussions/categories/python-packages++---++## FFI (Foreign Function Interface)++Access JavaScript APIs from Python via Pyodide's FFI:++### JavaScript Globals++```python+from js import fetch, console, Response as JSResponse++class Default(WorkerEntrypoint):+ async def fetch(self, request):+ # Use JavaScript fetch+ response = await fetch("https://api.example.com")+ data = await response.json()++ # Console logging+ console.log("Fetched data:", data)++ # Return JavaScript Response+ return JSResponse.new("Hello!")+```++### Type Conversions++```python+from js import Object+from pyodide.ffi import to_js++# Convert Python dict to JavaScript object+python_dict = {"name": "test", "count": 42}+js_object = to_js(python_dict, dict_converter=Object.fromEntries)++# Use in Response+return Response(to_js({"status": "ok"}))+```++---++## Known Issues Prevention++This skill prevents **8 documented issues**:++### Issue #1: Legacy Handler Pattern++**Error**: `TypeError: on_fetch is not defined`++**Why**: Handler pattern changed in August 2025.++```python+# ❌ OLD (deprecated)+@handler+async def on_fetch(request):+ return Response("Hello")++# ✅ NEW (current)+class Default(WorkerEntrypoint):+ async def fetch(self, request):+ return Response("Hello")+```++### Issue #2: Sync HTTP Libraries++**Error**: `RuntimeError: cannot use blocking call in async context`++**Why**: Python Workers run async-only. Sync libraries block the event loop.++```python+# ❌ FAILS+import requests+response = requests.get("https://api.example.com")++# ✅ WORKS+import httpx+async with httpx.AsyncClient() as client:+ response = await client.get("https://api.example.com")+```++### Issue #3: Native/Compiled Packages++**Error**: `ModuleNotFoundError: No module named 'numpy'` (or similar)++**Why**: Only pure Python packages work. Native C extensions are not supported.++**Solution**: Use Pyodide-compatible alternatives or check [Pyodide packages](https://pyodide.org/en/stable/usage/packages-in-pyodide.html).++### Issue #4: Missing Compatibility Flags++**Error**: `Error: Python Workers require the python_workers compatibility flag`++**Fix**: Add to wrangler.jsonc:++```jsonc+{+ "compatibility_flags": ["python_workers"]+}+```++For Workflows, also add `"python_workflows"`.++### Issue #5: I/O Outside Workflow Steps++**Error**: Workflow state not persisted correctly++**Why**: All I/O must happen inside `@step.do` for durability.++```python+# ❌ BAD - fetch outside step+response = await fetch("https://api.example.com")[email protected]("use data")+async def use_data():+ return await response.json() # response may be stale on retry++# ✅ GOOD - fetch inside step[email protected]("fetch and use")+async def fetch_and_use():+ response = await fetch("https://api.example.com")+ return await response.json()+```++### Issue #6: Type Serialization Errors++**Error**: `TypeError: Object of type X is not JSON serializable`++**Why**: Workflow step return values must be JSON-serializable.++**Fix**: Convert complex objects before returning:++```python[email protected]("process")+async def process():+ # Convert datetime to string+ return {"timestamp": datetime.now().isoformat()}+```++### Issue #7: Cold Start Performance++**Note**: Python Workers have higher cold starts than JavaScript (~1s vs ~50ms).++**Mitigation**:+- Minimize top-level imports+- Use lazy loading for heavy packages+- Consider JavaScript Workers for latency-critical paths++### Issue #8: Package Installation Failures++**Error**: `Failed to install package X`++**Causes**:+- Package has native dependencies+- Package not in Pyodide ecosystem+- Network issues during bundling++**Fix**: Check package compatibility, use alternatives, or request support.++---++## Best Practices++### Always Do++- Use `WorkerEntrypoint` class pattern+- Use async HTTP clients (httpx, aiohttp)+- Put all I/O inside workflow steps+- Add `python_workers` compatibility flag+- Use `self.env` for all bindings+- Return JSON-serializable data from workflow steps++### Never Do++- Use sync HTTP libraries (requests)+- Use native/compiled packages+- Perform I/O outside workflow steps+- Use legacy `@handler` decorator for fetch+- Expect JavaScript-level cold start times++---++## Framework Note: FastAPI++FastAPI can work with Python Workers but with limitations:++```python+from fastapi import FastAPI+from workers import WorkerEntrypoint++app = FastAPI()+[email protected]("/")+async def root():+ return {"message": "Hello from FastAPI"}++class Default(WorkerEntrypoint):+ async def fetch(self, request):+ # Route through FastAPI+ return await app(request)+```++**Limitations**:+- Async-only (no sync endpoints)+- No WSGI middleware+- Beta stability++See [Cloudflare FastAPI example](https://developers.cloudflare.com/workers/languages/python/) for details.++---++## Official Documentation++- [Python Workers Overview](https://developers.cloudflare.com/workers/languages/python/)+- [Python Workers Basics](https://developers.cloudflare.com/workers/languages/python/basics/)+- [How Python Workers Work](https://developers.cloudflare.com/workers/languages/python/how-python-workers-work/)+- [Python Packages](https://developers.cloudflare.com/workers/languages/python/packages/)+- [FFI (Foreign Function Interface)](https://developers.cloudflare.com/workers/languages/python/ffi/)+- [Python Workflows](https://developers.cloudflare.com/workflows/python/)+- [Pywrangler CLI](https://github.com/cloudflare/workers-py)+- [Pyodide Package List](https://pyodide.org/en/stable/usage/packages-in-pyodide.html)++---++## Dependencies++```json+{+ "workers-py": "latest",+ "workers-runtime-sdk": "latest",+ "wrangler": "^4.0.0"+}+```++---++## Production Validation++- Cloudflare changelog: Dec 8, 2025 (Pywrangler + cold start improvements)+- Python Workflows beta: Aug 22, 2025+- Handler pattern change: Aug 14, 2025diff --git a/skills/cloudflare-python-workers/references/common-issues.md b/skills/cloudflare-python-workers/references/common-issues.mdnew file mode 100644index 00000000..bf995ad0--- /dev/null+++ b/skills/cloudflare-python-workers/references/common-issues.md@@ -0,0 +1,353 @@+# Common Issues and Solutions++This document provides detailed solutions for common Python Workers issues.++## Issue #1: Legacy Handler Pattern++### Error Message+```+TypeError: on_fetch is not defined+```+or+```+Handler 'fetch' is not a function+```++### Cause+The handler pattern changed in August 2025. The old global function pattern is deprecated.++### Solution++**Old pattern (deprecated):**+```python+from workers import handler++@handler+async def on_fetch(request):+ return Response("Hello")+```++**New pattern (required):**+```python+from workers import WorkerEntrypoint, Response++class Default(WorkerEntrypoint):+ async def fetch(self, request):+ return Response("Hello")+```++### Temporary Workaround+If you must use the old pattern, add this compatibility flag:+```jsonc+{+ "compatibility_flags": ["python_workers", "disable_python_no_global_handlers"]+}+```++---++## Issue #2: Sync HTTP Library Errors++### Error Message+```+RuntimeError: cannot use blocking call in async context+```+or+```+RuntimeError: This event loop is already running+```++### Cause+Python Workers run in an async context. Synchronous HTTP libraries like `requests` block the event loop.++### Solution++Use async HTTP libraries:++```python+# ✅ httpx (recommended)+import httpx++async with httpx.AsyncClient() as client:+ response = await client.get("https://api.example.com")+ data = response.json()++# ✅ aiohttp+import aiohttp++async with aiohttp.ClientSession() as session:+ async with session.get("https://api.example.com") as response:+ data = await response.json()++# ✅ JavaScript fetch via FFI+from js import fetch++response = await fetch("https://api.example.com")+data = await response.json()+```++---++## Issue #3: Native Package Errors++### Error Messages+```+ModuleNotFoundError: No module named 'numpy'+```+```+ImportError: cannot import name 'xxx' from 'yyy'+```+```+Failed to install package: [package-name]+```++### Cause+Python Workers use Pyodide (Python compiled to WebAssembly). Native/compiled packages with C extensions don't work.++### Solution++1. **Check Pyodide compatibility**: https://pyodide.org/en/stable/usage/packages-in-pyodide.html++2. **Use pure Python alternatives**:+ - Instead of `numpy` → Use pure Python math or check if Pyodide has it+ - Instead of `pandas` → Use `polars` (if available) or process data manually+ - Instead of `requests` → Use `httpx` or `aiohttp`++3. **Request new packages**: https://github.com/cloudflare/workerd/discussions/categories/python-packages++---++## Issue #4: Missing Compatibility Flags++### Error Message+```+Error: Python Workers require the python_workers compatibility flag+```+or+```+Error: Workflows require the python_workflows compatibility flag+```++### Solution++Add flags to wrangler.jsonc:++```jsonc+{+ // For Python Workers only+ "compatibility_flags": ["python_workers"],++ // For Python Workflows+ "compatibility_flags": ["python_workers", "python_workflows"],++ // Minimum date for workflows+ "compatibility_date": "2025-08-01"+}+```++---++## Issue #5: Workflow I/O Outside Steps++### Symptoms+- Workflow state not persisted correctly+- Data appears stale after retry+- Inconsistent results++### Cause+I/O operations (fetch, database queries) outside of `@step.do` blocks are not durable.++### Solution++**Bad - I/O outside step:**+```python+async def run(self, event, step):+ # ❌ This fetch happens outside a step+ response = await fetch("https://api.example.com")++ @step.do("use_data")+ async def use_data():+ # If step retries, response is stale!+ return await response.json()+```++**Good - I/O inside step:**+```python+async def run(self, event, step):+ @step.do("fetch_and_use")+ async def fetch_and_use():+ # ✅ Fetch inside step - will retry properly+ response = await fetch("https://api.example.com")+ return await response.json()++ data = await fetch_and_use()+```++---++## Issue #6: JSON Serialization Errors++### Error Message+```+TypeError: Object of type datetime is not JSON serializable+```+```+TypeError: Object of type bytes is not JSON serializable+```++### Cause+Workflow step return values must be JSON-serializable for state persistence.++### Solution++Convert complex types before returning:++```python+from datetime import datetime+[email protected]("process")+async def process():+ # ❌ datetime is not JSON serializable+ # return {"time": datetime.now()}++ # ✅ Convert to string+ return {"time": datetime.now().isoformat()}+[email protected]("handle_bytes")+async def handle_bytes():+ data = b"binary data"++ # ❌ bytes not serializable+ # return {"data": data}++ # ✅ Encode as string+ return {"data": data.decode("utf-8")}+ # or base64 for binary+ import base64+ return {"data": base64.b64encode(data).decode("ascii")}+```++---++## Issue #7: Cold Start Performance++### Symptoms+- First request takes >1 second+- Timeout errors on cold starts+- Inconsistent latency++### Cause+Python Workers have higher cold starts than JavaScript (~1s vs ~50ms) due to Pyodide runtime initialization.++### Mitigation Strategies++1. **Lazy imports**: Don't import heavy packages at module level++```python+# ❌ Loads on every cold start+import heavy_package++class Default(WorkerEntrypoint):+ async def fetch(self, request):+ result = heavy_package.process()++# ✅ Load only when needed+class Default(WorkerEntrypoint):+ async def fetch(self, request):+ if need_heavy_processing:+ import heavy_package+ result = heavy_package.process()+```++2. **Use memory snapshots**: Deploy frequently - Cloudflare captures memory snapshots that improve subsequent cold starts.++3. **Consider JavaScript for latency-critical paths**: If <100ms latency is required, use JavaScript Workers.++---++## Issue #8: Package Installation Failures++### Error Messages+```+Failed to install package: [package-name]+```+```+Error: Package [name] has native dependencies+```+```+Network error during package installation+```++### Causes+1. Package has native C dependencies+2. Package not in Pyodide ecosystem+3. Network issues during pywrangler bundling++### Solutions++1. **Check Pyodide compatibility first**:+ ```bash+ # Check if package is in Pyodide+ # https://pyodide.org/en/stable/usage/packages-in-pyodide.html+ ```++2. **Use alternative packages**:+ - Many packages have pure-Python alternatives+ - Search PyPI for "pure python" versions++3. **Request support**:+ - https://github.com/cloudflare/workerd/discussions/categories/python-packages++4. **Retry installation**:+ ```bash+ # Clear cache and retry+ rm -rf .wrangler+ uv run pywrangler dev+ ```++---++## Debugging Tips++### Console Logging++```python+from js import console++class Default(WorkerEntrypoint):+ async def fetch(self, request):+ console.log("Request received:", request.url)+ console.error("This is an error")+ console.warn("This is a warning")+```++### View Logs++```bash+# Local development+uv run pywrangler dev+# Logs appear in terminal++# Production+wrangler tail+# or view in Cloudflare Dashboard+```++### Test Scheduled Handlers++```bash+# Enable test mode+uv run pywrangler dev --test-scheduled++# Trigger manually+curl "http://localhost:8787/cdn-cgi/handler/scheduled?cron=*+*+*+*+*"+```++---++## Resources++- [Python Workers Docs](https://developers.cloudflare.com/workers/languages/python/)+- [Pyodide Packages](https://pyodide.org/en/stable/usage/packages-in-pyodide.html)+- [Request New Packages](https://github.com/cloudflare/workerd/discussions/categories/python-packages)+- [Python Workers Discord](https://discord.cloudflare.com/) - #python-workers channeldiff --git a/skills/cloudflare-python-workers/templates/pyproject.toml b/skills/cloudflare-python-workers/templates/pyproject.tomlnew file mode 100644index 00000000..21401318--- /dev/null+++ b/skills/cloudflare-python-workers/templates/pyproject.toml@@ -0,0 +1,48 @@+[project]+name = "my-python-worker"+version = "0.1.0"+description = "A Python Worker on Cloudflare"+requires-python = ">=3.12"++# Add your production dependencies here+# Only pure Python packages work (no native/compiled packages)+# See: https://pyodide.org/en/stable/usage/packages-in-pyodide.html+dependencies = [+ # HTTP clients (async only!)+ # "httpx",+ # "aiohttp",++ # Common packages+ # "beautifulsoup4",+ # "pydantic",+]++[dependency-groups]+dev = [+ # Required for pywrangler CLI+ "workers-py",+ "workers-runtime-sdk",+]++[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++# ============================================+# NOTES+# ============================================+#+# Run locally:+# uv run pywrangler dev+#+# Deploy:+# uv run pywrangler deploy+#+# Add packages:+# uv add <package-name>+#+# IMPORTANT:+# - Only async HTTP libraries work (httpx, aiohttp)+# - Sync libraries like 'requests' will NOT work+# - Native/compiled packages (numpy, pandas) are NOT supported+# unless they're in the Pyodide ecosystemdiff --git a/skills/cloudflare-python-workers/templates/src/entry.py b/skills/cloudflare-python-workers/templates/src/entry.pynew file mode 100644index 00000000..04b56e6b--- /dev/null+++ b/skills/cloudflare-python-workers/templates/src/entry.py@@ -0,0 +1,128 @@+"""+Python Worker Entry Point++This is the main entry point for your Python Worker.+Uses the WorkerEntrypoint class pattern (required as of Aug 2025).+"""++from workers import WorkerEntrypoint, Response+import json+++class Default(WorkerEntrypoint):+ """+ Main Worker class.++ Handlers:+ - fetch: Handle HTTP requests+ - Access bindings via self.env (e.g., self.env.DB, self.env.MY_KV)+ """++ async def fetch(self, request):+ """+ Handle incoming HTTP requests.++ Args:+ request: The incoming Request object++ Returns:+ Response object+ """+ # Get request details+ url = request.url+ method = request.method++ # Route based on path+ path = url.split("?")[0].rstrip("/")++ if path.endswith("/api/hello"):+ return await self.handle_hello(request)++ if path.endswith("/api/data") and method == "POST":+ return await self.handle_post_data(request)++ # Default response+ return Response(+ json.dumps({+ "message": "Hello from Python Worker!",+ "method": method,+ "url": url,+ }),+ headers={"Content-Type": "application/json"}+ )++ async def handle_hello(self, request):+ """Handle GET /api/hello"""+ # Example: Access query parameters+ # url = URL(request.url)+ # name = url.searchParams.get("name", "World")++ return Response(+ json.dumps({"greeting": "Hello, World!"}),+ headers={"Content-Type": "application/json"}+ )++ async def handle_post_data(self, request):+ """Handle POST /api/data"""+ try:+ # Parse JSON body+ body = await request.json()++ # Process the data+ result = {+ "received": body,+ "processed": True+ }++ return Response(+ json.dumps(result),+ headers={"Content-Type": "application/json"}+ )++ except Exception as e:+ return Response(+ json.dumps({"error": str(e)}),+ status=400,+ headers={"Content-Type": "application/json"}+ )+++# ============================================+# BINDING EXAMPLES (uncomment as needed)+# ============================================++# async def example_d1_query(self):+# """Query D1 database"""+# result = await self.env.DB.prepare(+# "SELECT * FROM users WHERE id = ?"+# ).bind(1).first()+# return result++# async def example_kv_operations(self):+# """KV storage operations"""+# # Get+# value = await self.env.MY_KV.get("key")+#+# # Put+# await self.env.MY_KV.put("key", "value")+#+# # Delete+# await self.env.MY_KV.delete("key")++# async def example_r2_operations(self):+# """R2 object storage"""+# # Get object+# obj = await self.env.MY_BUCKET.get("file.txt")+# if obj:+# content = await obj.text()+#+# # Put object+# await self.env.MY_BUCKET.put("file.txt", "content")++# async def example_workers_ai(self):+# """Workers AI inference"""+# response = await self.env.AI.run(+# "@cf/meta/llama-2-7b-chat-int8",+# {"prompt": "Hello!"}+# )+# return responsediff --git a/skills/cloudflare-python-workers/templates/workflow-example.py b/skills/cloudflare-python-workers/templates/workflow-example.pynew file mode 100644index 00000000..807ec87b--- /dev/null+++ b/skills/cloudflare-python-workers/templates/workflow-example.py@@ -0,0 +1,213 @@+"""+Python Workflow Example++Demonstrates durable, multi-step workflows with:+- Step definitions using @step.do decorator+- DAG dependencies between steps+- Sleep/delay functionality+- Error handling++Requirements:+- Add "python_workflows" to compatibility_flags in wrangler.jsonc+- Add workflow binding configuration+"""++from workers import WorkflowEntrypoint, WorkerEntrypoint, Response+from js import fetch+import json+++class DataProcessingWorkflow(WorkflowEntrypoint):+ """+ Example workflow that fetches data, processes it, and stores results.++ Steps are automatically persisted and retried on failure.+ """++ async def run(self, event, step):+ """+ Main workflow execution.++ Args:+ event: Workflow event with payload+ step: Step helper for defining durable steps++ Returns:+ Final workflow result (must be JSON-serializable)+ """+ # Access payload passed when workflow was created+ payload = event.get("payload", {})++ # ============================================+ # STEP 1: Fetch external data+ # ============================================+ @step.do("fetch_data")+ async def fetch_data():+ """+ Fetch data from external API.++ IMPORTANT: All I/O (fetch, database, etc.) must be inside steps!+ This ensures durability - if the step fails, it will be retried.+ """+ url = payload.get("url", "https://api.example.com/data")+ response = await fetch(url)+ data = await response.json()+ return data++ data = await fetch_data()++ # ============================================+ # STEP 2: Wait/delay+ # ============================================+ await step.sleep("wait_before_processing", "5 seconds")++ # ============================================+ # STEP 3: Process data+ # ============================================+ @step.do("process_data")+ async def process_data():+ """Process the fetched data."""+ # Example processing+ processed = {+ "item_count": len(data) if isinstance(data, list) else 1,+ "processed_at": "2025-12-08T00:00:00Z", # Use string for JSON+ "status": "completed"+ }+ return processed++ result = await process_data()++ # ============================================+ # STEP 4: Store results (if using KV/D1)+ # ============================================+ # @step.do("store_results")+ # async def store_results():+ # await self.env.MY_KV.put(+ # f"result:{payload.get('id')}",+ # json.dumps(result)+ # )+ # return {"stored": True}+ #+ # await store_results()++ return result+++class DAGWorkflowExample(WorkflowEntrypoint):+ """+ Example of DAG (Directed Acyclic Graph) workflow with parallel steps.++ Steps can declare dependencies, and independent steps run concurrently.+ """++ async def run(self, event, step):+ # ============================================+ # Independent steps (can run in parallel)+ # ============================================+ @step.do("fetch_users")+ async def fetch_users():+ # Simulated fetch+ return [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]++ @step.do("fetch_products")+ async def fetch_products():+ # Simulated fetch+ return [{"id": 101, "name": "Widget"}]++ # ============================================+ # Dependent step (waits for both above)+ # ============================================+ @step.do("combine_data", depends=[fetch_users, fetch_products], concurrent=True)+ async def combine_data(users, products):+ """+ This step receives results from its dependencies.++ Args:+ users: Result from fetch_users+ products: Result from fetch_products+ """+ return {+ "user_count": len(users),+ "product_count": len(products),+ "combined": True+ }++ # Execute the DAG (dependencies resolve automatically)+ final_result = await combine_data()++ return final_result+++class Default(WorkerEntrypoint):+ """+ Worker entry point that triggers workflows.+ """++ async def fetch(self, request):+ """Handle HTTP requests and trigger workflows."""+ url = request.url+ path = url.split("?")[0].rstrip("/")++ # Start data processing workflow+ if path.endswith("/workflow/start"):+ try:+ body = await request.json()+ except:+ body = {}++ # Create workflow instance+ instance = await self.env.DATA_WORKFLOW.create(+ params={"payload": body}+ )++ return Response(+ json.dumps({+ "message": "Workflow started",+ "instance_id": instance.id+ }),+ headers={"Content-Type": "application/json"}+ )++ # Check workflow status+ if path.endswith("/workflow/status"):+ # Get instance ID from query params+ # instance = await self.env.DATA_WORKFLOW.get(instance_id)+ # status = await instance.status()+ return Response(+ json.dumps({"message": "Status endpoint"}),+ headers={"Content-Type": "application/json"}+ )++ return Response(+ json.dumps({+ "endpoints": [+ "POST /workflow/start - Start workflow",+ "GET /workflow/status?id=xxx - Check status"+ ]+ }),+ headers={"Content-Type": "application/json"}+ )+++# ============================================+# WRANGLER.JSONC CONFIGURATION+# ============================================+#+# Add to your wrangler.jsonc:+#+# {+# "compatibility_flags": ["python_workers", "python_workflows"],+# "compatibility_date": "2025-08-01",+# "workflows": [+# {+# "name": "data-processing-workflow",+# "binding": "DATA_WORKFLOW",+# "class_name": "DataProcessingWorkflow"+# },+# {+# "name": "dag-workflow-example",+# "binding": "DAG_WORKFLOW",+# "class_name": "DAGWorkflowExample"+# }+# ]+# }diff --git a/skills/cloudflare-python-workers/templates/wrangler.jsonc b/skills/cloudflare-python-workers/templates/wrangler.jsoncnew file mode 100644index 00000000..eaaf93e9--- /dev/null+++ b/skills/cloudflare-python-workers/templates/wrangler.jsonc@@ -0,0 +1,81 @@+{+ "$schema": "node_modules/wrangler/config-schema.json",++ // Project name - will be used as subdomain: <name>.workers.dev+ "name": "my-python-worker",++ // Entry point - your main Python file+ "main": "src/entry.py",++ // REQUIRED: Python Workers are in beta+ "compatibility_flags": ["python_workers"],++ // Use recent date for latest features+ "compatibility_date": "2025-12-01",++ // Optional: Account ID (avoids interactive prompts in CI/CD)+ // "account_id": "your-account-id-here",++ // ============================================+ // BINDINGS (uncomment as needed)+ // ============================================++ // D1 Database+ // "d1_databases": [+ // {+ // "binding": "DB",+ // "database_name": "my-database",+ // "database_id": "your-database-id"+ // }+ // ],++ // KV Namespace+ // "kv_namespaces": [+ // {+ // "binding": "MY_KV",+ // "id": "your-kv-namespace-id"+ // }+ // ],++ // R2 Bucket+ // "r2_buckets": [+ // {+ // "binding": "MY_BUCKET",+ // "bucket_name": "my-bucket"+ // }+ // ],++ // Workers AI+ // "ai": {+ // "binding": "AI"+ // },++ // Environment Variables+ // "vars": {+ // "MY_VAR": "my-value"+ // },++ // ============================================+ // WORKFLOWS (if using Python Workflows)+ // ============================================+ // Add "python_workflows" to compatibility_flags first!++ // "workflows": [+ // {+ // "name": "my-workflow",+ // "binding": "MY_WORKFLOW",+ // "class_name": "MyWorkflow"+ // }+ // ],++ // ============================================+ // CRON TRIGGERS (scheduled handlers)+ // ============================================++ // "triggers": {+ // "crons": [+ // "*/5 * * * *", // Every 5 minutes+ // "0 0 * * *" // Daily at midnight UTC+ // ]+ // }+}