celld中文文档v0.6.2
GitHub ↗
文档 / 入门与运行

python 示例源码

这些文件来自仓库的 examples/python,可结合对应中文文档阅读和运行。

wrangler.jsonc

json
{
  "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

python
# 向 /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

toml
[project]
name = "python-example"
version = "0.1.0"
requires-python = ">=3.13"
dependencies = ["beautifulsoup4"]

[dependency-groups]
dev = ["workers-py", "workers-runtime-sdk"]
celld v0.6.2 · 简体中文文档
产品名、API、命令与示例代码保留原始写法。

输入关键词,搜索 20 篇中文文档。

支持中文术语、API 与环境变量 · Esc 关闭