"""Exercise a local API workflow before and after a regression fix."""
from hashlib import sha256
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
from threading import Thread
from urllib.error import HTTPError
from urllib.parse import parse_qs, urlencode, urlsplit
from urllib.request import ProxyHandler, build_opener
import sys
def read_page(raw, records):
page = int(raw.get("page", ["1"])[0])
limit = int(raw.get("limit", ["2"])[0])
if page < 1 or not 1 <= limit <= 5:
raise ValueError("invalid pagination")
start = (page - 1) * limit
return records[start:start + limit]
def handler(fixed):
def response(request):
route = urlsplit(request.path)
if route.path == "/api/catalog":
records = ["A", "B", "C"]
try:
return 200, {"items": read_page(parse_qs(route.query, keep_blank_values=True), records)}
except ValueError:
return 400, {"error": "invalid pagination"}
if route.path == "/api/profile":
rows = {"known": {"id": 7}}
profile = rows.get(parse_qs(route.query).get("user", [""])[0])
if profile is None and fixed:
return 404, {"error": "profile not found"}
try:
return 200, {"id": profile["id"]}
except TypeError:
return 500, {"error": "could not load profile"}
return 404, {"error": "unknown route"}
class CatalogHandler(BaseHTTPRequestHandler):
def do_GET(self):
status, value = response(self)
output = json.dumps(value).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(output)))
self.end_headers()
self.wfile.write(output)
def log_message(self, format, *args):
pass
return CatalogHandler
def verify(fixed, inputs):
opener = build_opener(ProxyHandler({}))
output = []
with ThreadingHTTPServer(("127.0.0.1", 0), handler(fixed)) as server:
listener = Thread(target=server.serve_forever, daemon=True)
listener.start()
try:
for route, query in inputs:
address = f"http://127.0.0.1:{server.server_port}{route}?{urlencode(query)}"
try:
reply = opener.open(address, timeout=5)
except HTTPError as error:
reply = error
with reply:
output.append([reply.code, json.load(reply)])
finally:
server.shutdown()
listener.join(timeout=5)
return output
def main():
cases = []
def check(name, inputs, operation, expected, actual):
assert expected == actual, (name, expected, actual)
cases.append(dict(name="patterns_" + name, input=inputs, operation=operation, expected=expected, actual=actual))
pages = [("/api/catalog", {"page": 1, "limit": 2}),
("/api/catalog", {"page": 2, "limit": 2}),
("/api/catalog", {"page": 4, "limit": 2}),
("/api/catalog", {"page": 0, "limit": 2}),
("/api/catalog", {"page": 1, "limit": 6}),
("/api/catalog", {"page": 1, "limit": ""})]
result = [[200, {"items": ["A","B"]}], [200, {"items": ["C"]}], [200, {"items": []}]]
result.extend([[400, {"error": "invalid pagination"}]] * 3)
check("pagination", pages, "Issue GET requests to the temporary loopback service",
result, verify(False, pages))
check("unchanged", pages, "Repeat all pagination inputs after the unrelated profile fix",
result, verify(True, pages))
users = [("/api/profile", {"user": "known"}), ("/api/profile", {"user": "missing"})]
check("before", users, "Reproduce the missing profile error alongside a valid profile",
[[200, {"id": 7}], [500, {"error": "could not load profile"}]], verify(False, users))
check("after", users, "Check the missing profile now has a defined response and a normal read still works",
[[200, {"id": 7}], [404, {"error": "profile not found"}]], verify(True, users))
print(json.dumps(dict(version={"python":sys.version.split()[0],"runtime":"stdlib loopback HTTP"},
python_sha256=sha256(open(sys.executable,"rb").read()).hexdigest(),cases=cases)))
if __name__=="__main__":
main()
本例需在 Windows、Python 3.12.14 标准库、本机环回 HTTP。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14 标准库、本机环回 HTTP。
入口文件:projects/codex-workflow_patterns/workflow_patterns_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
workflow_patterns_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14 标准库、本机环回 HTTP。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a90.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a125.zip