python 示例源码
这些文件来自仓库的 examples/python,可结合对应中文文档阅读和运行。
wrangler.jsonc
{
"name": "python",
"main": "src/entry.py",
"compatibility_date": "2026-09-01",
"compatibility_flags": ["python_workers"],
"kv_namespaces": [
{
"binding": "PAGES",
"id": "example-pages"
}
]
}
src/entry.py
# 向 /summarize POST 一个 HTML 页面,获取标题和链接。摘要使用页面的
# SHA-256 作为键保存在 KV 中,GET /summary/<sha256> 可以读取。
import hashlib
import json
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from workers import Response, WorkerEntrypoint
def summarize(html):
soup = BeautifulSoup(html, "html.parser")
return {
"title": soup.title.get_text(strip=True) if soup.title else None,
"headings": [h.get_text(strip=True) for h in soup.select("h1, h2")],
"links": [a["href"] for a in soup.select("a[href]")],
}
class Default(WorkerEntrypoint):
async def fetch(self, request):
path = urlparse(request.url).path
if request.method == "POST" and path == "/summarize":
html = await request.text()
digest = hashlib.sha256(html.encode()).hexdigest()
summary = summarize(html)
await self.env.PAGES.put(digest, json.dumps(summary))
return Response.json({"sha256": digest, **summary})
if request.method == "GET" and path.startswith("/summary/"):
stored = await self.env.PAGES.get(path.removeprefix("/summary/"))
if stored is None:
return Response("not found", status=404)
return Response(stored, headers={"content-type": "application/json"})
return Response("POST HTML to /summarize\n", status=404)
pyproject.toml
[project]
name = "python-example"
version = "0.1.0"
requires-python = ">=3.13"
dependencies = ["beautifulsoup4"]
[dependency-groups]
dev = ["workers-py", "workers-runtime-sdk"]