蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 AppML 列表模板展开、表单模式联动、订单 setQuery 四表连接与综合 HTTP 实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-case-templates.py
explore-case-templates.py206 行
"""Offline CPython 3.12.14 verifier for AppML Ch08 (case-templates)."""
from html import escape
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import re
import sqlite3
import threading
from urllib.parse import parse_qs, urlparse
from urllib.request import urlopen


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.execute("CREATE TABLE Employees (EmployeeID INTEGER PRIMARY KEY, LastName TEXT, FirstName TEXT)")
    conn.execute("CREATE TABLE Shippers (ShipperID INTEGER PRIMARY KEY, ShipperName TEXT)")
    conn.execute("CREATE TABLE Orders (OrderID INTEGER PRIMARY KEY, CustomerID INTEGER, EmployeeID INTEGER, OrderDate TEXT, ShipperID INTEGER)")
    conn.executemany("INSERT INTO Customers VALUES (?, ?, ?, ?, ?)", [
        (1, "Around the Horn", "Thomas Hardy", "London", "UK"),
        (2, "Berglunds snabbkjøp", "Christina Berglund", "Luleå", "Sweden"),
    ])
    conn.executemany("INSERT INTO Employees VALUES (?, ?, ?)", [
        (1, "Davolio", "Nancy"),
        (2, "Fuller", "Andrew"),
    ])
    conn.executemany("INSERT INTO Shippers VALUES (?, ?)", [
        (1, "Speedy Express"),
        (2, "United Package"),
    ])
    conn.executemany("INSERT INTO Orders VALUES (?, ?, ?, ?, ?)", [
        (10355, 1, 1, "1996-11-15", 1),
        (10383, 1, 2, "1996-12-16", 2),
        (10278, 2, 2, "1996-08-12", 2),
    ])
    conn.commit()
    return conn


def bind_hash(template: str, row: dict) -> str:
    return re.sub(r"#([A-Za-z0-9_]+)#", lambda m: escape(str(row[m.group(1)])), template)


def run_cases() -> list[dict]:
    cases = []
    db = init_db()

    # Case 1: Template01 customer list binding (#Field# and modern {{Field}} parity)
    tpl1 = '<tr id="appml_row"><td>#CustomerName#</td><td>#City#</td><td>#Country#</td></tr>'
    customers = [dict(r) for r in db.execute("SELECT CustomerID, CustomerName, ContactName, City, Country FROM Customers ORDER BY CustomerID").fetchall()]
    rendered1 = [bind_hash(tpl1, c) for c in customers]
    modern_tpl = tpl1.replace("#CustomerName#", "{{CustomerName}}").replace("#City#", "{{City}}").replace("#Country#", "{{Country}}")
    modern_rendered = [
        re.sub(r"\{\{([A-Za-z0-9_]+)\}\}", lambda m: escape(str(c[m.group(1)])), modern_tpl)
        for c in customers
    ]
    actual1 = {
        "row_count": len(rendered1),
        "first_row": rendered1[0],
        "matches_mustache": rendered1 == modern_rendered,
    }
    expected1 = {
        "row_count": 2,
        "first_row": '<tr id="appml_row"><td>Around the Horn</td><td>London</td><td>UK</td></tr>',
        "matches_mustache": True,
    }
    cases.append({
        "name": "customer_list_template_binding",
        "summary": "Render hidden Template01 rows for Customers using #Field# placeholders and verify modern {{Field}} parity.",
        "expected": expected1,
        "actual": actual1,
        "passed": actual1 == expected1,
    })

    # Case 2: Master-detail list -> form binding (displayType="form", openForm(id))
    form_row_tpl = '<tr id="appml_row"><td onclick="openForm(\'#CustomerID#\')">Edit</td><td>#CustomerName#</td></tr>'
    trigger_html = bind_hash(form_row_tpl, customers[0])
    selected = dict(db.execute("SELECT * FROM Customers WHERE CustomerID = ?", (1,)).fetchone())
    form_model = {
        "container": "Form01",
        "displayType": "form",
        "template": "",
        "record_id": selected["CustomerID"],
        "fields": {k: selected[k] for k in ("CustomerName", "ContactName", "City", "Country")},
    }
    actual2 = {
        "trigger_has_id": "openForm(&#x27;1&#x27;)" in trigger_html or "openForm('1')" in trigger_html,
        "display_type": form_model["displayType"],
        "loaded_name": form_model["fields"]["CustomerName"],
        "loaded_city": form_model["fields"]["City"],
    }
    expected2 = {
        "trigger_has_id": True,
        "display_type": "form",
        "loaded_name": "Around the Horn",
        "loaded_city": "London",
    }
    cases.append({
        "name": "master_detail_form_binding",
        "summary": "Simulate openForm('#CustomerID#') with displayType='form' loading a single customer record by primary key.",
        "expected": expected2,
        "actual": actual2,
        "passed": actual2 == expected2,
    })

    # Case 3: Linked orders list using setQuery("orders.customerid", id) and commands=false
    orders_sql = (
        "SELECT c.CustomerName, o.OrderDate, (e.FirstName || ' ' || e.LastName) AS Salesperson, s.ShipperName "
        "FROM Orders o "
        "JOIN Customers c ON o.CustomerID = c.CustomerID "
        "JOIN Employees e ON o.EmployeeID = e.EmployeeID "
        "JOIN Shippers s ON o.ShipperID = s.ShipperID "
        "WHERE o.CustomerID = ? ORDER BY o.OrderID"
    )
    cust1_orders = [dict(r) for r in db.execute(orders_sql, (1,)).fetchall()]
    tpl2 = '<tr id="appml_row"><td>#CustomerName#</td><td>#OrderDate#</td><td>#Salesperson#</td><td>#ShipperName#</td></tr>'
    rendered_orders = [bind_hash(tpl2, o) for o in cust1_orders]
    actual3 = {
        "commands_enabled": False,
        "order_count": len(rendered_orders),
        "first_order_row": rendered_orders[0],
    }
    expected3 = {
        "commands_enabled": False,
        "order_count": 2,
        "first_order_row": '<tr id="appml_row"><td>Around the Horn</td><td>1996-11-15</td><td>Nancy Davolio</td><td>Speedy Express</td></tr>',
    }
    cases.append({
        "name": "linked_orders_setquery_filter",
        "summary": "Simulate orders.setQuery('orders.customerid', id) with commands=false and render Template02 joined order rows.",
        "expected": expected3,
        "actual": actual3,
        "passed": actual3 == expected3,
    })

    # Case 4: Combined master-detail HTTP workflow (List01 + List02)
    class CombinedHandler(BaseHTTPRequestHandler):
        def do_GET(self):
            qs = parse_qs(urlparse(self.path).query)
            model = qs.get("model", [""])[0]
            if model == "Models/Customers":
                rows = [dict(r) for r in db.execute("SELECT CustomerID, CustomerName, City, Country FROM Customers ORDER BY CustomerID").fetchall()]
                body = json.dumps({"records": rows}, ensure_ascii=False).encode("utf-8")
            elif model == "Models/Orders":
                cid = int(qs.get("orders.customerid", ["0"])[0])
                rows = [dict(r) for r in db.execute(orders_sql, (cid,)).fetchall()]
                body = json.dumps({"commands": False, "records": rows}, ensure_ascii=False).encode("utf-8")
            else:
                self.send_response(404)
                self.end_headers()
                return
            self.send_response(200)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.end_headers()
            self.wfile.write(body)

        def log_message(self, format, *args):
            return

    srv = HTTPServer(("127.0.0.1", 0), CombinedHandler)
    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.php?model=Models/Customers", timeout=5) as r:
            c_list = json.loads(r.read().decode("utf-8"))["records"]
        with urlopen(f"http://127.0.0.1:{port}/appml.php?model=Models/Orders&orders.customerid=2", timeout=5) as r:
            o_resp = json.loads(r.read().decode("utf-8"))
    finally:
        srv.shutdown()
        srv.server_close()
        db.close()

    actual4 = {
        "customers_count": len(c_list),
        "cust2_orders_count": len(o_resp["records"]),
        "cust2_first_shipper": o_resp["records"][0]["ShipperName"],
        "commands_disabled": o_resp["commands"] is False,
    }
    expected4 = {
        "customers_count": 2,
        "cust2_orders_count": 1,
        "cust2_first_shipper": "United Package",
        "commands_disabled": True,
    }
    cases.append({
        "name": "combined_app_http_workflow",
        "summary": "Verify combined Customers + filtered Orders HTTP controller responses with commands disabled on detail list.",
        "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-templates-lab/explore-case-templates.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-case-templates.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AppML

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3202.zip

下载课程关联工程包:AppML

课程关联工程包(登记关联13章) · 含当前章节或实例 · mbskycom202612a3195.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习