"""Offline CPython 3.12.14 verifier for AppML Ch01 (tutorial)."""
from html import escape
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import re
import sqlite3
import threading
from urllib.request import urlopen
import xml.etree.ElementTree as ET
MODEL_XML = """<appml>
<datasource>
<database>
<connection>Demo</connection>
<sql>SELECT CustomerName,City,Country FROM Customers</sql>
</database>
</datasource>
</appml>"""
TEMPLATE_ROW = (
'<tr id="appml_row"><td>#CustomerName#</td>'
'<td>#City#</td><td>#Country#</td></tr>'
)
SEED_CUSTOMERS = [
(1, "Alfreds Futterkiste", "Berlin", "Germany"),
(2, "Around the Horn", "London", "UK"),
(3, "Berglunds snabbkjøp", "Luleå", "Sweden"),
]
def init_db() -> sqlite3.Connection:
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
conn.execute(
"CREATE TABLE Customers ("
"CustomerID INTEGER PRIMARY KEY, "
"CustomerName TEXT NOT NULL, "
"City TEXT NOT NULL, "
"Country TEXT NOT NULL)"
)
conn.executemany(
"INSERT INTO Customers (CustomerID, CustomerName, City, Country) VALUES (?, ?, ?, ?)",
SEED_CUSTOMERS,
)
conn.commit()
return conn
def render_template(template: str, rows: list[dict], brace_style: str = "hash") -> list[str]:
pattern = re.compile(r"#([A-Za-z0-9_]+)#" if brace_style == "hash" else r"\{\{([A-Za-z0-9_]+)\}\}")
out = []
for row in rows:
out.append(pattern.sub(lambda m: escape(str(row[m.group(1)])), template))
return out
def run_cases() -> list[dict]:
cases = []
# Case 1: Parse XML model definition
root = ET.fromstring(MODEL_XML)
conn_name = (root.findtext("./datasource/database/connection") or "").strip()
sql_text = (root.findtext("./datasource/database/sql") or "").strip()
m = re.match(r"SELECT\s+(.+?)\s+FROM\s+(\w+)", sql_text, re.IGNORECASE)
cols = [c.strip() for c in m.group(1).split(",")] if m else []
table = m.group(2) if m else ""
actual1 = {"root": root.tag, "connection": conn_name, "table": table, "columns": cols}
expected1 = {
"root": "appml",
"connection": "Demo",
"table": "Customers",
"columns": ["CustomerName", "City", "Country"],
}
cases.append({
"name": "parse_appml_xml_model",
"summary": "Parse AppML XML model and extract connection, table, and projected columns.",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: Execute model SQL against in-memory SQLite
db = init_db()
rows = [dict(r) for r in db.execute(f"{sql_text} ORDER BY CustomerID").fetchall()]
actual2 = {
"row_count": len(rows),
"first_customer": rows[0]["CustomerName"],
"countries": [r["Country"] for r in rows],
}
expected2 = {
"row_count": 3,
"first_customer": "Alfreds Futterkiste",
"countries": ["Germany", "UK", "Sweden"],
}
cases.append({
"name": "sqlite_customers_query",
"summary": "Execute XML model SQL against local SQLite Customers table.",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: Render #Field# and modern {{Field}} template rows
rendered_hash = render_template(TEMPLATE_ROW, rows, brace_style="hash")
modern_tpl = TEMPLATE_ROW.replace("#CustomerName#", "{{CustomerName}}").replace("#City#", "{{City}}").replace("#Country#", "{{Country}}")
rendered_mustache = render_template(modern_tpl, rows, brace_style="mustache")
actual3 = {
"rendered_count": len(rendered_hash),
"first_row": rendered_hash[0],
"matches_modern_binding": rendered_hash == rendered_mustache,
}
expected3 = {
"rendered_count": 3,
"first_row": '<tr id="appml_row"><td>Alfreds Futterkiste</td><td>Berlin</td><td>Germany</td></tr>',
"matches_modern_binding": True,
}
cases.append({
"name": "render_appml_row_template",
"summary": "Expand #Field# placeholders in Template01 and verify parity with modern {{Field}} syntax.",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: Local HTTP MVC server serving JSON data and HTML view
payload_bytes = json.dumps({"model": "Models/Customers", "records": rows}, ensure_ascii=False).encode("utf-8")
html_bytes = (
"<!DOCTYPE html><html><body><h1>My First Web Application</h1>"
"<div id=\"Place01\"><table>" + "".join(rendered_hash) + "</table></div></body></html>"
).encode("utf-8")
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/appml?model=Customers":
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.end_headers()
self.wfile.write(payload_bytes)
else:
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(html_bytes)
def log_message(self, format, *args):
return
server = HTTPServer(("127.0.0.1", 0), Handler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
with urlopen(f"http://127.0.0.1:{port}/appml?model=Customers", timeout=5) as resp:
api_status = resp.status
api_data = json.loads(resp.read().decode("utf-8"))
with urlopen(f"http://127.0.0.1:{port}/index.html", timeout=5) as resp:
view_status = resp.status
view_html = resp.read().decode("utf-8")
finally:
server.shutdown()
server.server_close()
db.close()
actual4 = {
"api_status": api_status,
"view_status": view_status,
"api_record_count": len(api_data["records"]),
"view_has_first_customer": "Alfreds Futterkiste" in view_html,
}
expected4 = {
"api_status": 200,
"view_status": 200,
"api_record_count": 3,
"view_has_first_customer": True,
}
cases.append({
"name": "local_http_mvc_endpoint",
"summary": "Serve model JSON and rendered HTML view over local loopback HTTP to verify MVC separation.",
"expected": expected4,
"actual": actual4,
"passed": actual4 == expected4,
})
return cases
def main() -> None:
output = {
"version": "CPython 3.12.14 offline AppML model/template/SQLite verifier",
"cases": run_cases(),
}
print(json.dumps(output, 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-tutorial-lab/explore-tutorial.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3206.zip
课程关联工程包(登记关联13章) · 含当前章节或实例 · mbskycom202612a3195.zip