"""Offline CPython 3.12.14 verifier for AppML Ch05 (case-intro)."""
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import sqlite3
import threading
from urllib.parse import parse_qs, urlparse
from urllib.request import urlopen
CUSTOMERS_DATA = [
("Around the Horn", "120 Hanover Sq.", "London", "UK"),
("Berglunds snabbkjøp", "Berguvsvägen 8", "Luleå", "Sweden"),
("Blauer See Delikatessen", "Forsterstr. 57", "Mannheim", "Germany"),
("Blondel père et fils", "24, place Kléber", "Strasbourg", "France"),
("Bólido Comidas preparadas", "C/ Araquil, 67", "Madrid", "Spain"),
("Bottom-Dollar Markets", "23 Tsawassen Blvd.", "Tsawassen", "Canada"),
]
SUPPLIERS_DATA = [
("Exotic Liquid", "49 Gilbert St.", "London", "UK"),
("New Orleans Cajun Delights", "P.O. Box 78934", "New Orleans", "USA"),
("Grandma Kelly's Homestead", "707 Oxford Rd.", "Ann Arbor", "USA"),
("Tokyo Traders", "9-8 SekimaiMusashino-shi", "Tokyo", "Japan"),
("Cooperativa de Quesos 'Las Cabras'", "Calle del Rosal 4", "Oviedo", "Spain"),
("Mayumi's", "92 Setsuko Chuo-ku", "Osaka", "Japan"),
("Pavlova, Ltd.", "74 Rose St. Moonie Ponds", "Melbourne", "Australia"),
("Specialty Biscuits, Ltd.", "29 King's Way", "Manchester", "UK"),
("PB Knäckebröd AB", "Kaloadagatan 13", "Göteborg", "Sweden"),
("Refrescos Americanas LTDA", "Av. das Americanas 12.890", "São Paulo", "Brazil"),
]
# Source listing repeats Chai on row 4; keep a row_id primary key while recording both raw count and distinct names
PRODUCTS_DATA = [
("Chai", "10 boxes x 20 bags", 18, 39),
("Chang", "24 - 12 oz bottles", 19, 17),
("Aniseed Syrup", "12 - 550 ml bottles", 10, 13),
("Chai", "10 boxes x 20 bags", 18, 39),
("Chef Anton's Gumbo Mix", "36 boxes", 21, 0),
("Grandma's Boysenberry Spread", "12 - 8 oz jars", 25, 120),
("Uncle Bob's Organic Dried Pears", "12 - 1 lb pkgs.", 30, 15),
("Northwoods Cranberry Sauce", "12 - 12 oz jars", 40, 6),
("Mishi Kobe Niku", "18 - 500 g pkgs.", 97, 29),
("Ikura", "12 - 200 ml jars", 31, 31),
]
def init_demo_db() -> sqlite3.Connection:
conn = sqlite3.connect(":memory:", check_same_thread=False)
conn.row_factory = sqlite3.Row
conn.execute("CREATE TABLE Customers (CustomerID INTEGER PRIMARY KEY AUTOINCREMENT, Customer TEXT, Address TEXT, City TEXT, Country TEXT)")
conn.execute("CREATE TABLE Suppliers (SupplierID INTEGER PRIMARY KEY AUTOINCREMENT, Supplier TEXT, Address TEXT, City TEXT, Country TEXT)")
conn.execute("CREATE TABLE Products (ProductID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT, QuantityPerUnit TEXT, UnitPrice INTEGER, UnitsInStock INTEGER)")
conn.executemany("INSERT INTO Customers (Customer, Address, City, Country) VALUES (?, ?, ?, ?)", CUSTOMERS_DATA)
conn.executemany("INSERT INTO Suppliers (Supplier, Address, City, Country) VALUES (?, ?, ?, ?)", SUPPLIERS_DATA)
conn.executemany("INSERT INTO Products (ProductName, QuantityPerUnit, UnitPrice, UnitsInStock) VALUES (?, ?, ?, ?)", PRODUCTS_DATA)
conn.commit()
return conn
def run_cases() -> list[dict]:
cases = []
db = init_demo_db()
# Case 1: Load Northwind Demo tables and check counts + Unicode fidelity
c_cnt = db.execute("SELECT COUNT(*) FROM Customers").fetchone()[0]
s_cnt = db.execute("SELECT COUNT(*) FROM Suppliers").fetchone()[0]
p_cnt = db.execute("SELECT COUNT(*) FROM Products").fetchone()[0]
p_distinct = db.execute("SELECT COUNT(DISTINCT ProductName) FROM Products").fetchone()[0]
lulea = db.execute("SELECT City FROM Customers WHERE Customer = ?", ("Berglunds snabbkjøp",)).fetchone()[0]
actual1 = {
"customers": c_cnt,
"suppliers": s_cnt,
"products_rows": p_cnt,
"products_distinct": p_distinct,
"unicode_city": lulea,
}
expected1 = {
"customers": 6,
"suppliers": 10,
"products_rows": 10,
"products_distinct": 9,
"unicode_city": "Luleå",
}
cases.append({
"name": "northwind_demo_schema_load",
"summary": "Load Northwind Demo subset tables (Customers, Suppliers, Products) into SQLite and verify counts and UTF-8 text.",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: Verify 5-step case-study build pipeline
stages = [
"prototype_model",
"prototype_html",
"application_model",
"html_template",
"complete_application",
]
tables = ["Customers", "Suppliers", "Products"]
artifacts = {t: [f"{t}:{s}" for s in stages] for t in tables}
actual2 = {"stage_count": len(stages), "table_count": len(tables), "total_artifacts": sum(len(v) for v in artifacts.values())}
expected2 = {"stage_count": 5, "table_count": 3, "total_artifacts": 15}
cases.append({
"name": "case_study_five_stage_pipeline",
"summary": "Verify the 5-stage AppML case-study progression across Customers, Suppliers, and Products.",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: Cross-table analytical queries
uk_entities = (
db.execute("SELECT COUNT(*) FROM Customers WHERE Country='UK'").fetchone()[0]
+ db.execute("SELECT COUNT(*) FROM Suppliers WHERE Country='UK'").fetchone()[0]
)
out_of_stock = [r[0] for r in db.execute("SELECT ProductName FROM Products WHERE UnitsInStock = 0").fetchall()]
priciest = db.execute("SELECT ProductName, UnitPrice FROM Products ORDER BY UnitPrice DESC LIMIT 1").fetchone()
actual3 = {
"uk_total": uk_entities,
"out_of_stock": out_of_stock,
"priciest_product": priciest["ProductName"],
"priciest_price": priciest["UnitPrice"],
}
expected3 = {
"uk_total": 3,
"out_of_stock": ["Chef Anton's Gumbo Mix"],
"priciest_product": "Mishi Kobe Niku",
"priciest_price": 97,
}
cases.append({
"name": "cross_table_catalog_queries",
"summary": "Query UK customers/suppliers, zero-stock items, and highest-priced Northwind product in SQLite.",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: Local HTTP JSON endpoint serving the 3 Demo tables
allowed = {"Customers", "Suppliers", "Products"}
class DemoHandler(BaseHTTPRequestHandler):
def do_GET(self):
tbl = parse_qs(urlparse(self.path).query).get("table", ["Customers"])[0]
if tbl not in allowed:
self.send_response(400)
self.end_headers()
return
rows = [dict(r) for r in db.execute(f"SELECT * FROM {tbl}").fetchall()]
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.end_headers()
self.wfile.write(json.dumps({"table": tbl, "rows": rows}, ensure_ascii=False).encode("utf-8"))
def log_message(self, format, *args):
return
srv = HTTPServer(("127.0.0.1", 0), DemoHandler)
port = srv.server_address[1]
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
try:
counts = {}
for tbl in ("Customers", "Suppliers", "Products"):
with urlopen(f"http://127.0.0.1:{port}/demo?table={tbl}", timeout=5) as r:
counts[tbl] = len(json.loads(r.read().decode("utf-8"))["rows"])
finally:
srv.shutdown()
srv.server_close()
db.close()
expected4 = {"Customers": 6, "Suppliers": 10, "Products": 10}
cases.append({
"name": "northwind_json_service_preview",
"summary": "Expose Customers, Suppliers, and Products via local loopback HTTP JSON and verify row counts.",
"expected": expected4,
"actual": counts,
"passed": counts == 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-intro-lab/explore-case-intro.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-case-intro.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3198.zip
课程关联工程包(登记关联13章) · 含当前章节或实例 · mbskycom202612a3195.zip