"""Offline CPython 3.12.14 verifier for AppML Ch02 (howto)."""
from html import escape
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import re
import sqlite3
import threading
from urllib.request import Request, urlopen
import xml.etree.ElementTree as ET
CUSTOMERS_XML = """<appml>
<datasource>
<database>
<connection>Demo</connection>
<sql>SELECT CustomerName,ContactName,City,Country FROM Customers</sql>
<orderby>CustomerName</orderby>
</database>
</datasource>
<filters>
<query>
<field>CustomerName</field>
</query>
</filters>
</appml>"""
SEED_ROWS = [
(1, "Bottom-Dollar Markets", "Elizabeth Lincoln", "Tsawassen", "Canada"),
(2, "Alfreds Futterkiste", "Maria Anders", "Berlin", "Germany"),
(3, "Around the Horn", "Thomas Hardy", "London", "UK"),
(4, "Ana Trujillo Emparedados", "Ana Trujillo", "México D.F.", "Mexico"),
]
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 NOT NULL, "
"ContactName TEXT NOT NULL, "
"City TEXT NOT NULL, "
"Country TEXT NOT NULL)"
)
conn.executemany(
"INSERT INTO Customers VALUES (?, ?, ?, ?, ?)",
SEED_ROWS,
)
conn.commit()
return conn
def run_cases() -> list[dict]:
cases = []
# Case 1: Validate all 7 XML model tags
root = ET.fromstring(CUSTOMERS_XML)
tag_set = sorted({elem.tag for elem in root.iter()})
orderby = (root.findtext("./datasource/database/orderby") or "").strip()
filter_fields = [e.text.strip() for e in root.findall("./filters/query/field") if e.text]
actual1 = {
"tags": tag_set,
"connection": (root.findtext("./datasource/database/connection") or "").strip(),
"orderby": orderby,
"filter_fields": filter_fields,
}
expected1 = {
"tags": ["appml", "connection", "database", "datasource", "field", "filters", "orderby", "query", "sql"],
"connection": "Demo",
"orderby": "CustomerName",
"filter_fields": ["CustomerName"],
}
cases.append({
"name": "model_with_orderby_and_filters",
"summary": "Parse Customers.xml and verify datasource, database, orderby, and query filter declarations.",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: Progressive HTML -> CSS -> Script template structure check
step2_html = "<table><tr><th>Customer</th><th>City</th><th>Country</th></tr><tr><td>Alfreds Futterkiste</td><td>Berlin</td><td>Germany</td></tr></table>"
step3_html = '<link rel="stylesheet" href="appml.css"><table class="appmltable"><tr><th>Customer</th></tr></table>'
step4_html = '<div id="Place01"><table id="Template01" class="appmltable"><tr id="appml_row"><td>#CustomerName#</td><td>#City#</td><td>#Country#</td></tr></table></div>'
actual2 = {
"step2_plain_table": "<table" in step2_html and "appmltable" not in step2_html,
"step3_styled_table": 'href="appml.css"' in step3_html and 'class="appmltable"' in step3_html,
"step4_placeholders": re.findall(r"#([A-Za-z0-9_]+)#", step4_html),
"step4_has_hooks": 'id="Place01"' in step4_html and 'id="Template01"' in step4_html and 'id="appml_row"' in step4_html,
}
expected2 = {
"step2_plain_table": True,
"step3_styled_table": True,
"step4_placeholders": ["CustomerName", "City", "Country"],
"step4_has_hooks": True,
}
cases.append({
"name": "static_html_and_css_stages",
"summary": "Verify progressive steps from static HTML table to appml.css styling and Template01 hooks.",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: SQLite orderby + parameterized filter + template rendering
db = init_db()
base_sql = (root.findtext("./datasource/database/sql") or "").strip()
all_ordered = [dict(r) for r in db.execute(f"{base_sql} ORDER BY {orderby}").fetchall()]
filtered = [
dict(r)
for r in db.execute(
f"{base_sql} WHERE CustomerName LIKE ? ORDER BY {orderby}",
("A%",),
).fetchall()
]
tpl = '<tr id="appml_row"><td>#CustomerName#</td><td>#City#</td><td>#Country#</td></tr>'
rendered = [
re.sub(r"#([A-Za-z0-9_]+)#", lambda m: escape(str(row[m.group(1)])), tpl)
for row in filtered
]
actual3 = {
"ordered_names": [r["CustomerName"] for r in all_ordered],
"filtered_a_count": len(filtered),
"first_rendered_row": rendered[0],
}
expected3 = {
"ordered_names": [
"Alfreds Futterkiste",
"Ana Trujillo Emparedados",
"Around the Horn",
"Bottom-Dollar Markets",
],
"filtered_a_count": 3,
"first_rendered_row": '<tr id="appml_row"><td>Alfreds Futterkiste</td><td>Berlin</td><td>Germany</td></tr>',
}
cases.append({
"name": "run_template_binding_and_filter",
"summary": "Execute ORDER BY CustomerName and parameterized filter in SQLite, then expand #Field# row template.",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: Standard folder layout + local HTTP controller GET/POST cycle
layout = {
"folders": ["Demo", "Data", "Images", "Models"],
"app_files": ["Demo.htm", "Demo.css"],
"framework_files": ["appml_config.php", "appml.css", "appml.js", "appml.php"],
}
class Controller(BaseHTTPRequestHandler):
def do_GET(self):
rows = [dict(r) for r in db.execute("SELECT CustomerName, City, Country FROM Customers ORDER BY CustomerName").fetchall()]
body = json.dumps({"records": rows}, 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):
length = int(self.headers.get("Content-Length", "0"))
data = json.loads(self.rfile.read(length).decode("utf-8"))
db.execute(
"UPDATE Customers SET City = ? WHERE CustomerName = ?",
(data["City"], data["CustomerName"]),
)
db.commit()
resp = json.dumps({"updated": True, "City": data["City"]}).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.end_headers()
self.wfile.write(resp)
def log_message(self, format, *args):
return
server = HTTPServer(("127.0.0.1", 0), Controller)
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.php?model=Models/Customers.xml", timeout=5) as r:
initial_count = len(json.loads(r.read().decode("utf-8"))["records"])
req = Request(
f"http://127.0.0.1:{port}/appml.php?model=Models/Customers.xml",
data=json.dumps({"CustomerName": "Alfreds Futterkiste", "City": "Hamburg"}).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
with urlopen(req, timeout=5) as r:
post_res = json.loads(r.read().decode("utf-8"))
with urlopen(f"http://127.0.0.1:{port}/appml.php?model=Models/Customers.xml", timeout=5) as r:
after_rows = json.loads(r.read().decode("utf-8"))["records"]
updated_city = next(x["City"] for x in after_rows if x["CustomerName"] == "Alfreds Futterkiste")
finally:
server.shutdown()
server.server_close()
db.close()
actual4 = {
"layout_item_count": len(layout["folders"]) + len(layout["app_files"]) + len(layout["framework_files"]),
"initial_count": initial_count,
"post_updated": post_res["updated"],
"persisted_city": updated_city,
}
expected4 = {
"layout_item_count": 10,
"initial_count": 4,
"post_updated": True,
"persisted_city": "Hamburg",
}
cases.append({
"name": "project_directory_and_controller_flow",
"summary": "Validate the 10-entry AppML project layout and round-trip GET/POST controller persistence.",
"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-howto-lab/explore-howto.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-howto.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3204.zip
课程关联工程包(登记关联13章) · 含当前章节或实例 · mbskycom202612a3195.zip