"""Offline CPython 3.12.14 verifier for AppML Ch07 (case-models)."""
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import sqlite3
import threading
from urllib.error import HTTPError
from urllib.parse import parse_qs, urlparse
from urllib.request import Request, urlopen
import xml.etree.ElementTree as ET
FULL_CUSTOMERS_MODEL = """<appml security="">
<datasource>
<database>
<connection>Demo</connection>
<maintable>Customers</maintable>
<keyfield>CustomerID</keyfield>
<sql>SELECT * FROM Customers</sql>
<orderby>CustomerName,City,Country</orderby>
</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>
<update security="admin">
<item><name>CustomerName</name></item>
<item><name>ContactName</name></item>
<item><name>Address</name></item>
<item><name>PostalCode</name></item>
<item><name>City</name></item>
<item><name>Country</name></item>
</update>
</appml>"""
EMPLOYEE_UPDATE_XML = """<update security="admin">
<item><name>LastName</name></item>
<item><name>FirstName</name></item>
<item><name>BirthDate</name></item>
<item><name>Photo</name></item>
<item><name>Notes</name></item>
</update>"""
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, "
"Address TEXT, PostalCode TEXT, City TEXT, Country TEXT)"
)
conn.executemany(
"INSERT INTO Customers VALUES (?, ?, ?, ?, ?, ?, ?)",
[
(1, "Around the Horn", "Thomas Hardy", "120 Hanover Sq.", "WA1 1DP", "London", "UK"),
(2, "Berglunds snabbkjøp", "Christina Berglund", "Berguvsvägen 8", "S-958 22", "Luleå", "Sweden"),
(3, "Blauer See Delikatessen", "Hanna Moos", "Forsterstr. 57", "68306", "Mannheim", "Germany"),
],
)
conn.commit()
return conn
def check_role(required: str, user_roles: set[str]) -> bool:
if not required.strip():
return True
return required.strip() in user_roles
def run_cases() -> list[dict]:
cases = []
root = ET.fromstring(FULL_CUSTOMERS_MODEL)
db = init_db()
# Case 1: Parse <filters><query> and <order> + parameterized SQL execution
q_fields = [(f.text.strip(), f.attrib.get("label", f.text.strip())) for f in root.findall("./filters/query/field")]
o_fields = [(f.text.strip(), f.attrib.get("label", f.text.strip())) for f in root.findall("./filters/order/field")]
filtered = [dict(r) for r in db.execute("SELECT CustomerName, City, Country FROM Customers WHERE Country = ? ORDER BY CustomerName", ("UK",)).fetchall()]
actual1 = {
"query_fields": q_fields,
"order_fields": o_fields,
"uk_customer": filtered[0]["CustomerName"],
}
expected1 = {
"query_fields": [("CustomerName", "Customer"), ("City", "City"), ("Country", "Country")],
"order_fields": [("CustomerName", "Customer"), ("City", "City"), ("Country", "Country")],
"uk_customer": "Around the Horn",
}
cases.append({
"name": "parse_filters_query_and_order",
"summary": "Parse <filters> query/order fields and labels, then execute parameterized SQL filtering.",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: Parse <maintable>, <keyfield>, <update> allow-list + Employee snippet
maintable = (root.findtext("./datasource/database/maintable") or "").strip()
keyfield = (root.findtext("./datasource/database/keyfield") or "").strip()
cust_updatable = [e.text.strip() for e in root.findall("./update/item/name")]
emp_updatable = [e.text.strip() for e in ET.fromstring(EMPLOYEE_UPDATE_XML).findall("./item/name")]
# Reject unknown column, allow listed column
rejected_unknown = "CustomerID" not in cust_updatable
db.execute(f"UPDATE {maintable} SET City = ? WHERE {keyfield} = ?", ("Bristol", 1))
db.commit()
new_city = db.execute("SELECT City FROM Customers WHERE CustomerID = 1").fetchone()[0]
actual2 = {
"maintable": maintable,
"keyfield": keyfield,
"cust_updatable_count": len(cust_updatable),
"emp_updatable": emp_updatable,
"rejected_keyfield_overwrite": rejected_unknown,
"updated_city": new_city,
}
expected2 = {
"maintable": "Customers",
"keyfield": "CustomerID",
"cust_updatable_count": 6,
"emp_updatable": ["LastName", "FirstName", "BirthDate", "Photo", "Notes"],
"rejected_keyfield_overwrite": True,
"updated_city": "Bristol",
}
cases.append({
"name": "parse_update_and_keyfield",
"summary": "Verify <maintable>, <keyfield>, and <update> field allow-lists for Customers and Employees models.",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: Model-level and update-level security attribute checks
strict_root_sec = "admin"
open_root_sec = root.attrib.get("security", "")
update_sec = root.find("./update").attrib.get("security", "")
actual3 = {
"strict_model_guest_read": check_role(strict_root_sec, {"guest"}),
"strict_model_admin_read": check_role(strict_root_sec, {"admin"}),
"customers_guest_read": check_role(open_root_sec, {"guest"}),
"customers_guest_update": check_role(update_sec, {"guest"}),
"customers_admin_update": check_role(update_sec, {"admin"}),
}
expected3 = {
"strict_model_guest_read": False,
"strict_model_admin_read": True,
"customers_guest_read": True,
"customers_guest_update": False,
"customers_admin_update": True,
}
cases.append({
"name": "security_role_access_control",
"summary": "Verify <appml security='admin'> vs open read with <update security='admin'> authorization rules.",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: Full Customers.xml HTTP endpoint + 8-model switcher check
models = ["Customers", "Products", "Suppliers", "Shippers", "Categories", "Employees", "Orders", "OrderDetails"]
class ModelHandler(BaseHTTPRequestHandler):
def do_GET(self):
model = parse_qs(urlparse(self.path).query).get("model", [""])[0]
if model == "Models/Customers":
rows = [dict(r) for r in db.execute("SELECT * FROM Customers ORDER BY CustomerName, City, Country").fetchall()]
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.end_headers()
self.wfile.write(json.dumps({"records": rows}, ensure_ascii=False).encode("utf-8"))
else:
self.send_response(404)
self.end_headers()
def do_POST(self):
role = self.headers.get("X-Role", "guest")
if not check_role(update_sec, {role}):
self.send_response(403)
self.end_headers()
return
payload = json.loads(self.rfile.read(int(self.headers.get("Content-Length", "0"))).decode("utf-8"))
col = payload["field"]
if col not in cust_updatable:
self.send_response(400)
self.end_headers()
return
db.execute(f"UPDATE Customers SET {col} = ? WHERE CustomerID = ?", (payload["value"], payload["id"]))
db.commit()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(b'{"updated":true}')
def log_message(self, format, *args):
return
srv = HTTPServer(("127.0.0.1", 0), ModelHandler)
port = srv.server_address[1]
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
try:
guest_code = None
try:
urlopen(Request(
f"http://127.0.0.1:{port}/appml.php",
data=json.dumps({"id": 1, "field": "City", "value": "Leeds"}).encode("utf-8"),
headers={"Content-Type": "application/json", "X-Role": "guest"},
method="POST",
), timeout=5)
except HTTPError as err:
guest_code = err.code
with urlopen(Request(
f"http://127.0.0.1:{port}/appml.php",
data=json.dumps({"id": 1, "field": "City", "value": "London"}).encode("utf-8"),
headers={"Content-Type": "application/json", "X-Role": "admin"},
method="POST",
), timeout=5) as r:
admin_code = r.status
with urlopen(f"http://127.0.0.1:{port}/appml.php?model=Models/Customers", timeout=5) as r:
recs = json.loads(r.read().decode("utf-8"))["records"]
finally:
srv.shutdown()
srv.server_close()
db.close()
actual4 = {
"guest_post_code": guest_code,
"admin_post_code": admin_code,
"restored_city": recs[0]["City"],
"switcher_models_count": len(models),
}
expected4 = {
"guest_post_code": 403,
"admin_post_code": 200,
"restored_city": "London",
"switcher_models_count": 8,
}
cases.append({
"name": "full_customers_model_and_switcher",
"summary": "Execute complete Models/Customers read/admin-update HTTP workflow and verify 8-model switcher catalog.",
"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-models-lab/explore-case-models.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-case-models.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3199.zip
课程关联工程包(登记关联13章) · 含当前章节或实例 · mbskycom202612a3195.zip