"""Offline Playwright Chromium lab for AngularJS Ch 10 (http)."""
import http.server
import json
import threading
from playwright.sync_api import sync_playwright
SITES_PAYLOAD = {
"sites": [
{"Name": "BlueSky", "Url": "www.example.com", "Country": "CN"},
{"Name": "MDN", "Url": "developer.mozilla.org", "Country": "USA"},
{"Name": "W3C", "Url": "www.w3.org", "Country": "USA"},
{"Name": "Gitee", "Url": "gitee.com", "Country": "CN"},
]
}
INDEX_HTML = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>AngularJS $http Offline Lab</title></head>
<body>
<ul id="sites-list"></ul>
<script>
(function () {
function $http(config) {
const method = (config.method || "GET").toUpperCase();
const opts = { method, headers: Object.assign({}, config.headers || {}) };
if (config.data !== undefined && method !== "GET" && method !== "HEAD") {
opts.headers["Content-Type"] = "application/json";
opts.body = JSON.stringify(config.data);
}
const p = fetch(config.url, opts).then(async (res) => {
const text = method === "HEAD" ? "" : await res.text();
let data = text;
try {
if (text) data = JSON.parse(text);
} catch (_) {}
const resp = {
data,
status: res.status,
statusText: res.statusText,
config
};
if (res.ok) return resp;
return Promise.reject(resp);
});
// Legacy <1.5 .success()/.error() shim for contrast testing only
p.success = function (fn) {
p.then((resp) => fn(resp.data, resp.status, () => null, config));
return p;
};
p.error = function (fn) {
p.then(null, (resp) => fn(resp.data, resp.status, () => null, config));
return p;
};
return p;
}
$http.get = (url, cfg = {}) => $http(Object.assign({}, cfg, { method: "GET", url }));
$http.head = (url, cfg = {}) => $http(Object.assign({}, cfg, { method: "HEAD", url }));
$http.post = (url, data, cfg = {}) => $http(Object.assign({}, cfg, { method: "POST", url, data }));
$http.put = (url, data, cfg = {}) => $http(Object.assign({}, cfg, { method: "PUT", url, data }));
$http.delete = (url, cfg = {}) => $http(Object.assign({}, cfg, { method: "DELETE", url }));
$http.patch = (url, data, cfg = {}) => $http(Object.assign({}, cfg, { method: "PATCH", url, data }));
$http.jsonp = (url, cfg = {}) => $http(Object.assign({}, cfg, { method: "GET", url }));
window.$http = $http;
window.renderSites = function (sites) {
const ul = document.getElementById("sites-list");
ul.innerHTML = "";
for (const x of sites) {
const li = document.createElement("li");
li.textContent = x.Name + ", " + x.Country;
ul.appendChild(li);
}
};
})();
</script>
</body>
</html>
"""
class ApiHandler(http.server.BaseHTTPRequestHandler):
def _send_json(self, status, obj):
body = json.dumps(obj, 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 == "/":
body = INDEX_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(body)))
self.end_headers()
self.wfile.write(body)
elif self.path == "/api/sites.json":
self._send_json(200, SITES_PAYLOAD)
elif self.path == "/api/missing":
self._send_json(404, {"error": "not found"})
else:
self._send_json(404, {"error": "unknown"})
def do_HEAD(self):
if self.path == "/api/sites.json":
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.end_headers()
else:
self.send_response(404)
self.end_headers()
def _read_json(self):
length = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(length).decode("utf-8") if length else "{}"
return json.loads(raw)
def do_POST(self):
if self.path == "/api/submit":
payload = self._read_json()
self._send_json(201, {"ok": True, "method": "POST", "received": payload})
else:
self._send_json(404, {"error": "unknown"})
def do_PUT(self):
payload = self._read_json()
self._send_json(200, {"ok": True, "method": "PUT", "received": payload})
def do_PATCH(self):
payload = self._read_json()
self._send_json(200, {"ok": True, "method": "PATCH", "received": payload})
def do_DELETE(self):
self._send_json(200, {"ok": True, "method": "DELETE"})
def log_message(self, format, *args):
pass
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), ApiHandler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.goto(f"http://127.0.0.1:{port}/", wait_until="load")
# Case 1: $http({method:'GET', url:'/api/sites.json'}).then(...)
actual_1 = page.evaluate("""async () => {
const res = await window.$http({ method: 'GET', url: '/api/sites.json' });
window.renderSites(res.data.sites);
return {
status: res.status,
site_count: res.data.sites.length,
rendered_items: Array.from(document.querySelectorAll('#sites-list li')).map(li => li.textContent)
};
}""")
expected_1 = {
"status": 200,
"site_count": 4,
"rendered_items": ["BlueSky, CN", "MDN, USA", "W3C, USA", "Gitee, CN"],
}
cases.append({
"name": "http_config_get_then_success",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: Shorthand $http.get & $http.post
actual_2 = page.evaluate("""async () => {
const getRes = await window.$http.get('/api/sites.json');
const postRes = await window.$http.post('/api/submit', { name: 'AngularJS', version: '1.x' });
return {
get_status: getRes.status,
get_first_site: getRes.data.sites[0].Name,
post_status: postRes.status,
post_echo: postRes.data.received
};
}""")
expected_2 = {
"get_status": 200,
"get_first_site": "BlueSky",
"post_status": 201,
"post_echo": {"name": "AngularJS", "version": "1.x"},
}
cases.append({
"name": "http_shorthand_get_and_post",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: Error callback on HTTP 404
actual_3 = page.evaluate("""async () => {
return await window.$http({ method: 'GET', url: '/api/missing' }).then(
() => ({ branch: 'success' }),
(errResp) => ({ branch: 'error', status: errResp.status, error: errResp.data.error })
);
}""")
expected_3 = {"branch": "error", "status": 404, "error": "not found"}
cases.append({
"name": "http_error_callback_404",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: All 7 shorthand methods exist & HEAD/PUT/PATCH/DELETE execute
actual_4 = page.evaluate("""async () => {
const names = ['get', 'head', 'post', 'put', 'delete', 'jsonp', 'patch'];
const allPresent = names.every((m) => typeof window.$http[m] === 'function');
const headRes = await window.$http.head('/api/sites.json');
const putRes = await window.$http.put('/api/item/1', { title: 'updated' });
const patchRes = await window.$http.patch('/api/item/1', { active: true });
const delRes = await window.$http.delete('/api/item/1');
return {
all_7_shorthands_present: allPresent,
head_status: headRes.status,
put_method: putRes.data.method,
patch_method: patchRes.data.method,
delete_method: delRes.data.method
};
}""")
expected_4 = {
"all_7_shorthands_present": True,
"head_status": 200,
"put_method": "PUT",
"patch_method": "PATCH",
"delete_method": "DELETE",
}
cases.append({
"name": "http_shorthand_methods_inventory",
"expected": expected_4,
"actual": actual_4,
"passed": actual_4 == expected_4,
})
# Case 5: v1.5+ .then(response.data.sites) vs legacy <1.5 .success(data.sites)
actual_5 = page.evaluate("""async () => {
const thenRes = await window.$http.get('/api/sites.json').then((response) => ({
has_wrapper_data: Array.isArray(response.data.sites),
has_status: response.status === 200,
count: response.data.sites.length
}));
const legacyRes = await new Promise((resolve) => {
window.$http.get('/api/sites.json').success((payload) => {
resolve({
direct_sites_array: Array.isArray(payload.sites),
count: payload.sites.length
});
});
});
return { v15_then: thenRes, legacy_success: legacyRes };
}""")
expected_5 = {
"v15_then": {"has_wrapper_data": True, "has_status": True, "count": 4},
"legacy_success": {"direct_sites_array": True, "count": 4},
}
cases.append({
"name": "http_v15_then_vs_deprecated_success",
"expected": expected_5,
"actual": actual_5,
"passed": actual_5 == expected_5,
})
browser.close()
finally:
server.shutdown()
server.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/angularjs-http-lab/explore-http.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-http.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联26章) · 含当前章节或实例 · mbskycom202612a851.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a862.zip