Diffinery

homeflare/celldpublic

34 lines · 1.4 KBRaw History
1# POST an HTML page to /summarize to get its title and links. The summary is
2# kept in KV under the page's SHA-256, and GET /summary/<sha256> reads it back.
3import hashlib
4import json
5from urllib.parse import urlparse
6
7from bs4 import BeautifulSoup
8from workers import Response, WorkerEntrypoint
9
10
11def summarize(html):
12 soup = BeautifulSoup(html, "html.parser")
13 return {
14 "title": soup.title.get_text(strip=True) if soup.title else None,
15 "headings": [h.get_text(strip=True) for h in soup.select("h1, h2")],
16 "links": [a["href"] for a in soup.select("a[href]")],
17 }
18
19
20class Default(WorkerEntrypoint):
21 async def fetch(self, request):
22 path = urlparse(request.url).path
23 if request.method == "POST" and path == "/summarize":
24 html = await request.text()
25 digest = hashlib.sha256(html.encode()).hexdigest()
26 summary = summarize(html)
27 await self.env.PAGES.put(digest, json.dumps(summary))
28 return Response.json({"sha256": digest, **summary})
29 if request.method == "GET" and path.startswith("/summary/"):
30 stored = await self.env.PAGES.get(path.removeprefix("/summary/"))
31 if stored is None:
32 return Response("not found", status=404)
33 return Response(stored, headers={"content-type": "application/json"})
34 return Response("POST HTML to /summarize\n", status=404)