"""Offline Playwright Chromium verification for React Ch21 (ajax)."""
import http.server
import json
import threading
import time
from playwright.sync_api import sync_playwright
def launch_browser(p):
for kwargs in (
dict(headless=True),
dict(headless=True, channel="chrome"),
dict(headless=True, channel="msedge"),
):
try:
return p.chromium.launch(**kwargs)
except Exception:
continue
raise RuntimeError("No Chromium/Chrome/Edge browser executable available")
class LocalApiHandler(http.server.BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
def _send_json(self, status, payload):
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path == "/":
html = """<!doctype html>
<html><head><meta charset="utf-8"><title>React AJAX Lab</title></head>
<body><div id="root"></div></body></html>""".encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(html)))
self.end_headers()
self.wfile.write(html)
elif self.path == "/api/data":
self._send_json(200, {"id": 101, "title": "React Async Guide", "items": ["fetch", "axios"]})
elif self.path == "/api/fail":
self._send_json(500, {"error": "Internal Server Error"})
elif self.path == "/api/slow":
time.sleep(0.45)
try:
self._send_json(200, {"username": "octocat", "gistUrl": "https://gist.local/octocat/1"})
except (BrokenPipeError, ConnectionAbortedError, ConnectionResetError):
pass
else:
self._send_json(404, {"error": "Not Found"})
def do_POST(self):
if self.path == "/api/items":
length = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(length).decode("utf-8") if length else "{}"
data = json.loads(raw)
self._send_json(201, {"created": True, "name": data.get("name", ""), "count": 1})
else:
self._send_json(404, {"error": "Not Found"})
def case_fetch_useeffect_loading_and_json(page, base_url):
page.goto(base_url + "/")
actual = page.evaluate("""async () => {
const root = document.getElementById('root');
let state = { data: null, loading: true };
const snapshots = [];
function render() {
if (state.loading) {
root.innerHTML = '<div id="status">Loading...</div>';
} else {
root.innerHTML = '<h1>Data from API:</h1><pre id="out">' + JSON.stringify(state.data) + '</pre>';
}
snapshots.push(root.textContent.trim());
}
render();
// Simulate useEffect(..., []) running after mount
const res = await fetch('/api/data');
const json = await res.json();
state = { data: json, loading: false };
render();
return {
initialText: snapshots[0],
finalHeading: root.querySelector('h1').textContent,
parsedData: JSON.parse(root.querySelector('#out').textContent),
loadingAfter: state.loading,
};
}""")
expected = {
"initialText": "Loading...",
"finalHeading": "Data from API:",
"parsedData": {"id": 101, "title": "React Async Guide", "items": ["fetch", "axios"]},
"loadingAfter": False,
}
return dict(name="fetch_useeffect_loading_and_json", expected=expected, actual=actual, passed=(actual == expected))
def case_fetch_error_try_catch_and_post(page, base_url):
page.goto(base_url + "/")
actual = page.evaluate("""async () => {
let caughtError = null;
let rawOk = null;
try {
const res = await fetch('/api/fail');
rawOk = res.ok;
if (!res.ok) {
throw new Error('HTTP ' + res.status);
}
} catch (err) {
caughtError = err.message;
}
const postRes = await fetch('/api/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'useEffect-demo' }),
});
const postJson = await postRes.json();
return {
fetch500OkFlag: rawOk,
caughtError,
postStatus: postRes.status,
postJson,
};
}""")
expected = {
"fetch500OkFlag": False,
"caughtError": "HTTP 500",
"postStatus": 201,
"postJson": {"created": True, "name": "useEffect-demo", "count": 1},
}
return dict(name="fetch_error_try_catch_and_post", expected=expected, actual=actual, passed=(actual == expected))
def case_axios_style_client_response_data(page, base_url):
page.goto(base_url + "/")
actual = page.evaluate("""async () => {
const miniAxios = {
async get(url) {
const res = await fetch(url);
const data = await res.json();
if (res.status < 200 || res.status >= 300) {
const err = new Error('Request failed with status code ' + res.status);
err.response = { status: res.status, data };
throw err;
}
return { status: res.status, data };
}
};
const okResp = await miniAxios.get('/api/data');
let failMsg = null;
let failStatus = null;
await miniAxios.get('/api/fail').catch((err) => {
failMsg = err.message;
failStatus = err.response.status;
});
return {
okStatus: okResp.status,
okTitle: okResp.data.title,
failStatus,
failMsg,
};
}""")
expected = {
"okStatus": 200,
"okTitle": "React Async Guide",
"failStatus": 500,
"failMsg": "Request failed with status code 500",
}
return dict(name="axios_style_client_response_data", expected=expected, actual=actual, passed=(actual == expected))
def case_unmount_abort_controller_cleanup(page, base_url):
page.goto(base_url + "/")
actual = page.evaluate("""async () => {
const controller = new AbortController();
let mounted = true;
let setStateCallsAfterUnmount = 0;
let errorName = null;
let abortedFlag = false;
const reqPromise = (async () => {
try {
const res = await fetch('/api/slow', { signal: controller.signal });
const data = await res.json();
if (!mounted) {
setStateCallsAfterUnmount += 1;
}
return data;
} catch (err) {
errorName = err.name;
abortedFlag = controller.signal.aborted;
return null;
}
})();
// Simulate component unmount cleanup before slow request finishes
await new Promise((r) => setTimeout(r, 60));
mounted = false;
controller.abort();
const result = await reqPromise;
return {
abortedFlag,
errorName,
result,
setStateCallsAfterUnmount,
};
}""")
expected = {
"abortedFlag": True,
"errorName": "AbortError",
"result": None,
"setStateCallsAfterUnmount": 0,
}
return dict(name="unmount_abort_controller_cleanup", expected=expected, actual=actual, passed=(actual == expected))
def main():
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), LocalApiHandler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
base_url = f"http://127.0.0.1:{port}"
try:
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
cases = [
case_fetch_useeffect_loading_and_json(page, base_url),
case_fetch_error_try_catch_and_post(page, base_url),
case_axios_style_client_response_data(page, base_url),
case_unmount_abort_controller_cleanup(page, base_url),
]
finally:
browser.close()
finally:
server.shutdown()
server.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/react-ajax-lab/explore-ajax.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-ajax.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3151.zip