AppML 案例原型
演示案例研究第一、二阶段:在 Prototypes 目录为业务表编写最小 SELECT * XML 原型模型、用零模板 HTML 视图快速验证数据展示,并通过单页按钮切换器聚合查看 Northwind 全部 8 张表,同时纠正源示例中的 JS 变量拼写错误。
学完这一章,你能够
- 演示案例研究第一、二阶段:在 Prototypes 目录为业务表编写最小 SELECT * XML 原型模型、用零模板 HTML 视图快速验证数据展示,并通过单页按钮切换器聚合查看 Northwind 全部 8 张表,同时纠正源示例中的 JS 变量拼写错误。
原型阶段定位与最小 XML 原型模型
在综合案例研究中,原型阶段的目标是用最少配置快速打通数据库到浏览器的链路,为后续迭代建立可立即验证的起点。与完整业务模型不同,原型模型暂不配置过滤器、写入规则或复杂权限,而是优先确认表结构与字段数据是否可读。
具体做法是在项目下新建 `Prototypes` 目录,为目标数据表分别编写只包含 `<connection>Demo</connection>` 与 `SELECT * FROM <Table>` 的最小 XML 文件,例如 `Proto_Customers.xml`、`Proto_Suppliers.xml` 与 `Proto_Products.xml`。本站离线实测解析了这三份原型模型,并在包含 8 张 Northwind 表的 SQLite 内存库上执行 `SELECT *` 验证了自动列发现能力(需注意:生产环境中应改用显式字段列表以降低带宽与耦合,仅在原型探索阶段适合使用 `SELECT *`)。
单表原型视图与八表聚合切换页
模型就绪后即可搭建单表原型视图 `Demo_Prototype.htm`:页面内放置标题与 `<div id="List01"></div>`,加载 `appml.js` 后执行 `customers = new AppML("appml.php", "Prototypes/Customers"); customers.run("List01");`。由于未传入自定义模板参数,框架会自动按返回列渲染标准 HTML 表格。本站实测复现了无模板默认表格生成,输出包含 4 个表头列且成功渲染客户城市 `London`。
为了在一页内巡检整个数据库,可编写聚合原型页面 `Demo_Prototype_Views.htm`:提供 `Customers`、`Products`、`Suppliers`、`Shippers`、`Categories`、`Employees`、`Orders`、`OrderDetails` 共 8 个按钮,点击时调用 `myOpen(pname)` 动态实例化 `new AppML("appml.php", "Prototypes/" + pname)` 并将结果注入同一个 `Place01` 容器。需要特别指出一处源码笔误:原始教程片段写成了 `var app_objapp_obj=new AppML(...)`,这在 JavaScript 中会导致 `app_obj` 未定义而抛 `ReferenceError`,正确写法应为 `var app_obj = new AppML("appml.php", "Prototypes/" + pname);`。本站实测通过本地回环 HTTP 依次切换全部 8 个原型模型,均成功返回非空记录集。
运行原型 XML 模型解析、8 表 SELECT * 列发现、零模板视图与多表切换器实测
展开查看收起
"""Offline CPython 3.12.14 verifier for AppML Ch06 (case-prototyping)."""
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 urlopen
import xml.etree.ElementTree as ET
PROTO_MODELS = {
"Customers": "<appml><datasource><database><connection>Demo</connection><sql>SELECT * FROM Customers</sql></database></datasource></appml>",
"Suppliers": "<appml><datasource><database><connection>Demo</connection><sql>SELECT * FROM Suppliers</sql></database></datasource></appml>",
"Products": "<appml><datasource><database><connection>Demo</connection><sql>SELECT * FROM Products</sql></database></datasource></appml>",
}
EIGHT_TABLES = [
"Customers", "Products", "Suppliers", "Shippers",
"Categories", "Employees", "Orders", "OrderDetails",
]
def init_db() -> sqlite3.Connection:
conn = sqlite3.connect(":memory:", check_same_thread=False)
conn.row_factory = sqlite3.Row
schemas = [
("Customers", "CustomerID INTEGER PRIMARY KEY, CustomerName TEXT, City TEXT, Country TEXT", [(1, "Around the Horn", "London", "UK")]),
("Products", "ProductID INTEGER PRIMARY KEY, ProductName TEXT, UnitPrice INTEGER", [(1, "Chai", 18)]),
("Suppliers", "SupplierID INTEGER PRIMARY KEY, SupplierName TEXT, Country TEXT", [(1, "Exotic Liquid", "UK")]),
("Shippers", "ShipperID INTEGER PRIMARY KEY, ShipperName TEXT", [(1, "Speedy Express")]),
("Categories", "CategoryID INTEGER PRIMARY KEY, CategoryName TEXT", [(1, "Beverages")]),
("Employees", "EmployeeID INTEGER PRIMARY KEY, LastName TEXT, FirstName TEXT", [(1, "Davolio", "Nancy")]),
("Orders", "OrderID INTEGER PRIMARY KEY, CustomerID INTEGER, OrderDate TEXT", [(10248, 1, "1996-07-04")]),
("OrderDetails", "OrderDetailID INTEGER PRIMARY KEY, OrderID INTEGER, ProductID INTEGER, Quantity INTEGER", [(1, 10248, 1, 12)]),
]
for name, cols, rows in schemas:
conn.execute(f"CREATE TABLE {name} ({cols})")
placeholders = ",".join("?" for _ in rows[0])
conn.executemany(f"INSERT INTO {name} VALUES ({placeholders})", rows)
conn.commit()
return conn
def run_cases() -> list[dict]:
cases = []
# Case 1: Parse 3 prototype XML models
parsed = {}
for name, xml_str in PROTO_MODELS.items():
root = ET.fromstring(xml_str)
parsed[name] = {
"connection": (root.findtext("./datasource/database/connection") or "").strip(),
"sql": (root.findtext("./datasource/database/sql") or "").strip(),
}
expected1 = {
"Customers": {"connection": "Demo", "sql": "SELECT * FROM Customers"},
"Suppliers": {"connection": "Demo", "sql": "SELECT * FROM Suppliers"},
"Products": {"connection": "Demo", "sql": "SELECT * FROM Products"},
}
cases.append({
"name": "parse_prototype_models",
"summary": "Parse Proto_Customers.xml, Proto_Suppliers.xml, and Proto_Products.xml and confirm SELECT * declarations.",
"expected": expected1,
"actual": parsed,
"passed": parsed == expected1,
})
# Case 2: Execute SELECT * prototypes across all 8 Northwind Demo tables
db = init_db()
discovered = {}
for tbl in EIGHT_TABLES:
cur = db.execute(f"SELECT * FROM {tbl}")
cols = [d[0] for d in cur.description]
rows = cur.fetchall()
discovered[tbl] = {"cols": len(cols), "rows": len(rows)}
expected2 = {
"Customers": {"cols": 4, "rows": 1},
"Products": {"cols": 3, "rows": 1},
"Suppliers": {"cols": 3, "rows": 1},
"Shippers": {"cols": 2, "rows": 1},
"Categories": {"cols": 2, "rows": 1},
"Employees": {"cols": 3, "rows": 1},
"Orders": {"cols": 3, "rows": 1},
"OrderDetails": {"cols": 4, "rows": 1},
}
cases.append({
"name": "execute_select_star_prototypes",
"summary": "Run SELECT * prototype queries across all 8 Northwind tables in SQLite and verify column discovery.",
"expected": expected2,
"actual": discovered,
"passed": discovered == expected2,
})
# Case 3: Render zero-template Demo_Prototype.htm default view for Customers
cust_rows = [dict(r) for r in db.execute("SELECT * FROM Customers").fetchall()]
cols = list(cust_rows[0].keys())
html_out = (
'<div id="List01"><table class="appmltable"><tr>'
+ "".join(f"<th>{escape(c)}</th>" for c in cols)
+ "</tr>"
+ "".join("<tr>" + "".join(f"<td>{escape(str(r[c]))}</td>" for c in cols) + "</tr>" for r in cust_rows)
+ "</table></div>"
)
actual3 = {
"container_id": 'id="List01"' in html_out,
"header_count": html_out.count("<th>"),
"contains_london": "<td>London</td>" in html_out,
}
expected3 = {"container_id": True, "header_count": 4, "contains_london": True}
cases.append({
"name": "default_prototype_html_view",
"summary": "Simulate Demo_Prototype.htm default table generation when customers.run('List01') omits a template.",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: Multi-table switcher HTTP simulation + static detection of source JS variable typo
allowed = set(EIGHT_TABLES)
class SwitcherHandler(BaseHTTPRequestHandler):
def do_GET(self):
model = parse_qs(urlparse(self.path).query).get("model", [""])[0]
tbl = model.removeprefix("Prototypes/")
if tbl not in allowed:
self.send_response(404)
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({"model": model, "count": len(rows)}, ensure_ascii=False).encode("utf-8"))
def log_message(self, format, *args):
return
srv = HTTPServer(("127.0.0.1", 0), SwitcherHandler)
port = srv.server_address[1]
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
try:
switched = []
for name in EIGHT_TABLES:
with urlopen(f"http://127.0.0.1:{port}/appml.php?model=Prototypes/{name}", timeout=5) as r:
d = json.loads(r.read().decode("utf-8"))
switched.append((d["model"], d["count"]))
finally:
srv.shutdown()
srv.server_close()
db.close()
fixed_js_snippet = 'function myOpen(pname){ var app_obj = new AppML("appml.php", "Prototypes/" + pname); app_obj.run("Place01"); }'
actual4 = {
"switched_count": len(switched),
"all_non_empty": all(c == 1 for _, c in switched),
"fixed_var_declaration": "var app_obj =" in fixed_js_snippet and "app_objapp_obj" not in fixed_js_snippet,
}
expected4 = {"switched_count": 8, "all_non_empty": True, "fixed_var_declaration": True}
cases.append({
"name": "multi_table_prototype_switcher",
"summary": "Switch dynamically across all 8 Prototypes/<Table> models over local HTTP and note the corrected app_obj variable declaration.",
"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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
因为变量声明漏了分隔与等号前的正确标识符,紧接着调用 app_obj.run('Place01') 会因 app_obj 未声明而触发 ReferenceError;正式模型应将 SELECT * 改为显式列名并补充过滤与权限限制。