"""Offline CPython 3.12.14 verifier for AppML Ch11 (case-products)."""
from html import escape
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import re
import sqlite3
import threading
from urllib.parse import parse_qs, urlparse
from urllib.request import Request, urlopen
def init_db() -> sqlite3.Connection:
conn = sqlite3.connect(":memory:", check_same_thread=False)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
conn.execute("CREATE TABLE Categories (CategoryID INTEGER PRIMARY KEY, CategoryName TEXT NOT NULL)")
conn.execute("CREATE TABLE Suppliers (SupplierID INTEGER PRIMARY KEY, SupplierName TEXT NOT NULL)")
conn.execute(
"CREATE TABLE Products ("
"ProductID INTEGER PRIMARY KEY, ProductName TEXT NOT NULL, "
"SupplierID INTEGER NOT NULL REFERENCES Suppliers(SupplierID), "
"CategoryID INTEGER NOT NULL REFERENCES Categories(CategoryID), "
"Unit TEXT NOT NULL, Price REAL NOT NULL)"
)
conn.executemany("INSERT INTO Categories VALUES (?, ?)", [
(1, "Beverages"),
(2, "Condiments"),
(8, "Seafood"),
])
conn.executemany("INSERT INTO Suppliers VALUES (?, ?)", [
(1, "Exotic Liquid"),
(2, "New Orleans Cajun Delights"),
(4, "Tokyo Traders"),
])
conn.executemany("INSERT INTO Products VALUES (?, ?, ?, ?, ?, ?)", [
(1, "Chai", 1, 1, "10 boxes x 20 bags", 18.0),
(2, "Aniseed Syrup", 1, 2, "12 - 550 ml bottles", 10.0),
(3, "Ikura", 4, 8, "12 - 200 ml jars", 31.0),
])
conn.commit()
return conn
def bind_hash(tpl: str, row: dict) -> str:
return re.sub(r"#([A-Za-z0-9_]+)#", lambda m: escape(str(row[m.group(1)])), tpl)
def run_cases() -> list[dict]:
cases = []
db = init_db()
join_sql = (
"SELECT p.ProductID, p.ProductName, c.CategoryName, s.SupplierName, p.Unit, p.Price, p.SupplierID, p.CategoryID "
"FROM Products p "
"JOIN Categories c ON p.CategoryID = c.CategoryID "
"JOIN Suppliers s ON p.SupplierID = s.SupplierID "
"ORDER BY p.ProductID"
)
# Case 1: Template01 joined Products list rendering
tpl1 = (
'<tr id="appml_row">'
'<td onclick="productForm.run(\'Form01\',\'Template02\',\'#ProductID#\')">+</td>'
'<td>#ProductName#</td><td>#CategoryName#</td><td>#SupplierName#</td></tr>'
)
products = [dict(r) for r in db.execute(join_sql).fetchall()]
rendered1 = [bind_hash(tpl1, p) for p in products]
actual1 = {
"product_count": len(rendered1),
"first_row_has_join": "<td>Chai</td><td>Beverages</td><td>Exotic Liquid</td>" in rendered1[0],
"first_row_has_trigger": "productForm.run('Form01','Template02','1')" in rendered1[0],
}
expected1 = {"product_count": 3, "first_row_has_join": True, "first_row_has_trigger": True}
cases.append({
"name": "products_joined_list_template",
"summary": "Join Products with Categories and Suppliers and render Template01 list rows.",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: Resolve data-appmlapplication dropdown models (Suppliers & Categories)
suppliers = [dict(r) for r in db.execute("SELECT SupplierID, SupplierName FROM Suppliers ORDER BY SupplierID").fetchall()]
categories = [dict(r) for r in db.execute("SELECT CategoryID, CategoryName FROM Categories ORDER BY CategoryID").fetchall()]
selected_product = products[0]
sup_options = [
f'<option value="{s["SupplierID"]}"{" selected" if s["SupplierID"] == selected_product["SupplierID"] else ""}>{escape(s["SupplierName"])}</option>'
for s in suppliers
]
cat_options = [
f'<option value="{c["CategoryID"]}"{" selected" if c["CategoryID"] == selected_product["CategoryID"] else ""}>{escape(c["CategoryName"])}</option>'
for c in categories
]
actual2 = {
"supplier_options_count": len(sup_options),
"category_options_count": len(cat_options),
"selected_supplier_option": next(o for o in sup_options if " selected" in o),
"selected_category_option": next(o for o in cat_options if " selected" in o),
}
expected2 = {
"supplier_options_count": 3,
"category_options_count": 3,
"selected_supplier_option": '<option value="1" selected>Exotic Liquid</option>',
"selected_category_option": '<option value="1" selected>Beverages</option>',
}
cases.append({
"name": "dropdown_foreign_key_models",
"summary": "Populate SupplierID and CategoryID <select> controls from Dropdown_Suppliers and Dropdown_Categories models.",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: Form UPDATE with foreign key integrity enforcement
fk_rejected = False
try:
db.execute("UPDATE Products SET SupplierID = ? WHERE ProductID = ?", (999, 1))
db.commit()
except sqlite3.IntegrityError:
fk_rejected = True
db.rollback()
db.execute(
"UPDATE Products SET SupplierID = ?, CategoryID = ?, Price = ? WHERE ProductID = ?",
(2, 2, 19.5, 1),
)
db.commit()
updated = dict(db.execute(join_sql).fetchall()[0])
actual3 = {
"invalid_fk_rejected": fk_rejected,
"updated_supplier": updated["SupplierName"],
"updated_category": updated["CategoryName"],
"updated_price": updated["Price"],
}
expected3 = {
"invalid_fk_rejected": True,
"updated_supplier": "New Orleans Cajun Delights",
"updated_category": "Condiments",
"updated_price": 19.5,
}
cases.append({
"name": "products_form_update_fk_validation",
"summary": "Enforce SQLite foreign key constraints when updating Products SupplierID, CategoryID, and Price.",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: Static JS fix check (without executing source scripts) + HTTP Products & Dropdown API
fixed_js = 'var products, productForm;\nproducts = new AppML("appml.php", "Models/Products");'
class ProdHandler(BaseHTTPRequestHandler):
def do_GET(self):
model = parse_qs(urlparse(self.path).query).get("model", [""])[0]
if model == "Models/Products":
data = {"records": [dict(r) for r in db.execute(join_sql).fetchall()]}
elif model == "Models/Dropdown_Suppliers":
data = {"records": [dict(r) for r in db.execute("SELECT SupplierID, SupplierName FROM Suppliers ORDER BY SupplierID").fetchall()]}
elif model == "Models/Dropdown_Categories":
data = {"records": [dict(r) for r in db.execute("SELECT CategoryID, CategoryName FROM Categories ORDER BY CategoryID").fetchall()]}
else:
self.send_response(404)
self.end_headers()
return
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.end_headers()
self.wfile.write(json.dumps(data, ensure_ascii=False).encode("utf-8"))
def log_message(self, format, *args):
return
srv = HTTPServer(("127.0.0.1", 0), ProdHandler)
port = srv.server_address[1]
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
try:
with urlopen(f"http://127.0.0.1:{port}/appml.php?model=Models/Products", timeout=5) as r:
p_recs = json.loads(r.read().decode("utf-8"))["records"]
with urlopen(f"http://127.0.0.1:{port}/appml.php?model=Models/Dropdown_Suppliers", timeout=5) as r:
s_recs = json.loads(r.read().decode("utf-8"))["records"]
with urlopen(f"http://127.0.0.1:{port}/appml.php?model=Models/Dropdown_Categories", timeout=5) as r:
c_recs = json.loads(r.read().decode("utf-8"))["records"]
finally:
srv.shutdown()
srv.server_close()
db.close()
actual4 = {
"products_count": len(p_recs),
"suppliers_count": len(s_recs),
"categories_count": len(c_recs),
"js_typo_fixed": "productForm;" in fixed_js and "productFormproducts" not in fixed_js,
}
expected4 = {"products_count": 3, "suppliers_count": 3, "categories_count": 3, "js_typo_fixed": True}
cases.append({
"name": "products_static_code_and_http_api",
"summary": "Serve Products and both dropdown models over local HTTP and statically verify corrected JS declaration.",
"expected": expected4,
"actual": actual4,
"passed": actual4 == expected4,
})
return cases
def main() -> None:
print(json.dumps({
"version": "CPython 3.12.14 offline AppML model/template/SQLite verifier",
"cases": run_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/appml-case-products-lab/explore-case-products.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-case-products.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3200.zip
课程关联工程包(登记关联13章) · 含当前章节或实例 · mbskycom202612a3195.zip