"""Offline CPython 3.12.14 verifier for AppML Ch04 (architecture)."""
from html import escape
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import sqlite3
import threading
from urllib.parse import parse_qs, urlparse
from urllib.request import Request, urlopen
import xml.etree.ElementTree as ET
MODEL_XML = """<appml>
<datasource>
<database>
<connection>Northwind</connection>
<sql>SELECT CustomerName,ContactName,City,Country FROM Customers</sql>
</database>
</datasource>
<filters>
<query>
<field label="Customer">CustomerName</field>
<field>City</field>
<field>Country</field>
</query>
<order>
<field label="Customer">CustomerName</field>
<field>City</field>
<field>Country</field>
</order>
</filters>
</appml>"""
def init_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, "
"CustomerName TEXT, ContactName TEXT, City TEXT, Country TEXT)"
)
conn.executemany(
"INSERT INTO Customers VALUES (?, ?, ?, ?, ?)",
[
(1, "Around the Horn", "Thomas Hardy", "London", "UK"),
(2, "Blauer See Delikatessen", "Hanna Moos", "Mannheim", "Germany"),
(3, "Berglunds snabbkjøp", "Christina Berglund", "Luleå", "Sweden"),
],
)
conn.commit()
return conn
def render_default_table(rows: list[dict], labels: dict[str, str]) -> str:
if not rows:
return "<table></table>"
cols = list(rows[0].keys())
head = "".join(f"<th>{escape(labels.get(c, c))}</th>" for c in cols)
body = "".join(
"<tr>" + "".join(f"<td>{escape(str(r[c]))}</td>" for c in cols) + "</tr>"
for r in rows
)
return f'<table class="appmltable"><tr>{head}</tr>{body}</table>'
def run_cases() -> list[dict]:
cases = []
# Case 1: Parse MVC XML model with query & order filters and label attributes
root = ET.fromstring(MODEL_XML)
conn_name = (root.findtext("./datasource/database/connection") or "").strip()
query_fields = [(f.text.strip(), f.attrib.get("label", f.text.strip())) for f in root.findall("./filters/query/field")]
order_fields = [(f.text.strip(), f.attrib.get("label", f.text.strip())) for f in root.findall("./filters/order/field")]
actual1 = {
"connection": conn_name,
"query_fields": query_fields,
"order_fields": order_fields,
}
expected1 = {
"connection": "Northwind",
"query_fields": [("CustomerName", "Customer"), ("City", "City"), ("Country", "Country")],
"order_fields": [("CustomerName", "Customer"), ("City", "City"), ("Country", "Country")],
}
cases.append({
"name": "mvc_xml_model_separation",
"summary": "Parse Northwind XML model and extract query/order allow-lists and display labels.",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: Controller HTTP GET/POST + role authorization + SQLite persistence
db = init_db()
allowed_query = {f[0] for f in query_fields}
allowed_order = {f[0] for f in order_fields}
class AppMLController(BaseHTTPRequestHandler):
def do_GET(self):
parsed = urlparse(self.path)
qs = parse_qs(parsed.query)
where_clauses, params = [], []
for k, vals in qs.items():
if k in allowed_query and vals:
where_clauses.append(f"{k} = ?")
params.append(vals[0])
order_col = qs.get("order", ["CustomerName"])[0]
if order_col not in allowed_order:
order_col = "CustomerName"
sql = "SELECT CustomerName, ContactName, City, Country FROM Customers"
if where_clauses:
sql += " WHERE " + " AND ".join(where_clauses)
sql += f" ORDER BY {order_col}"
records = [dict(r) for r in db.execute(sql, params).fetchall()]
body = json.dumps({"connection": conn_name, "records": records}, ensure_ascii=False).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.end_headers()
self.wfile.write(body)
def do_POST(self):
role = self.headers.get("X-AppML-Role", "guest")
if role != "admin":
self.send_response(403)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(b'{"error":"forbidden"}')
return
data = json.loads(self.rfile.read(int(self.headers.get("Content-Length", "0"))).decode("utf-8"))
db.execute("UPDATE Customers SET City = ? WHERE CustomerName = ?", (data["City"], data["CustomerName"]))
db.commit()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps({"ok": True}).encode("utf-8"))
def log_message(self, format, *args):
return
srv = HTTPServer(("127.0.0.1", 0), AppMLController)
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?order=City", timeout=5) as r:
ordered = json.loads(r.read().decode("utf-8"))["records"]
# Guest update must be rejected (403)
guest_status = None
try:
req_guest = Request(
f"http://127.0.0.1:{port}/appml",
data=json.dumps({"CustomerName": "Around the Horn", "City": "Oxford"}).encode("utf-8"),
headers={"Content-Type": "application/json", "X-AppML-Role": "guest"},
method="POST",
)
urlopen(req_guest, timeout=5)
except Exception as exc:
guest_status = getattr(exc, "code", None)
# Admin update must succeed (200)
req_admin = Request(
f"http://127.0.0.1:{port}/appml",
data=json.dumps({"CustomerName": "Around the Horn", "City": "Manchester"}).encode("utf-8"),
headers={"Content-Type": "application/json", "X-AppML-Role": "admin"},
method="POST",
)
with urlopen(req_admin, timeout=5) as r:
admin_status = r.status
with urlopen(f"http://127.0.0.1:{port}/appml?Country=UK", timeout=5) as r:
uk_rows = json.loads(r.read().decode("utf-8"))["records"]
finally:
srv.shutdown()
srv.server_close()
actual2 = {
"ordered_cities": [r["City"] for r in ordered],
"guest_update_status": guest_status,
"admin_update_status": admin_status,
"updated_uk_city": uk_rows[0]["City"],
}
expected2 = {
"ordered_cities": ["London", "Luleå", "Mannheim"],
"guest_update_status": 403,
"admin_update_status": 200,
"updated_uk_city": "Manchester",
}
cases.append({
"name": "controller_read_and_update_cycle",
"summary": "Verify server controller GET query/sort, guest 403 security enforcement, and admin POST persistence.",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: Declarative Code-First SQL generation vs SOA data service
filter_country = "Germany"
assert "Country" in allowed_query
rows_de = [dict(r) for r in db.execute("SELECT CustomerName, City, Country FROM Customers WHERE Country = ?", (filter_country,)).fetchall()]
soa_envelope = {
"protocol": "HTTP/1.1",
"format": "JSON",
"stateless": True,
"declarative_model": "Customers.xml",
"data": rows_de,
}
actual3 = {
"de_count": len(rows_de),
"de_customer": rows_de[0]["CustomerName"],
"soa_stateless": soa_envelope["stateless"],
}
expected3 = {
"de_count": 1,
"de_customer": "Blauer See Delikatessen",
"soa_stateless": True,
}
cases.append({
"name": "declarative_code_first_vs_soa",
"summary": "Verify declarative XML model drives parameterized SQL and lightweight HTTP/JSON SOA data output.",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: Zero-template default HTML view rendering (customers.run("Place01")) and folder manifest
all_rows = [dict(r) for r in db.execute("SELECT CustomerName, City, Country FROM Customers ORDER BY CustomerID").fetchall()]
db.close()
default_html = render_default_table(all_rows, {"CustomerName": "Customer"})
folder_items = ["Demo", "Data", "Images", "Models", "Demo.htm", "Demo.css", "appml_config.php", "appml.css", "appml.js", "appml.php"]
actual4 = {
"has_customer_header": "<th>Customer</th>" in default_html,
"tr_count": default_html.count("<tr>"),
"folder_layout_entries": len(folder_items),
}
expected4 = {
"has_customer_header": True,
"tr_count": 4,
"folder_layout_entries": 10,
}
cases.append({
"name": "default_view_and_folder_layout",
"summary": "Render zero-template default HTML table from model labels and verify the 10-entry web directory structure.",
"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-architecture-lab/explore-architecture.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-architecture.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3194.zip
课程关联工程包(登记关联13章) · 含当前章节或实例 · mbskycom202612a3195.zip