蓝色天空.知识 · 实践 · 创造
我的收藏
AppML 教程目录 13章
AppML / LEARN BY DOING

AppML 案例 Products

解析 Products 商品管理应用案例中的多表连接列表与外键下拉框绑定(`data-appmlapplication` 加载供应商与分类模型),静态核对 8 个嵌入元素与源码声明笔误,并在 SQLite 开启外键约束实测表单更新。

学完这一章,你能够

  • 解析 Products 商品管理应用案例中的多表连接列表与外键下拉框绑定(`data-appmlapplication` 加载供应商与分类模型),静态核对 8 个嵌入元素与源码声明笔误,并在 SQLite 开启外键约束实测表单更新。

Products 连接列表与外键下拉表单

Products 案例进一步展示了存在外键关联时的表单编辑模式。页面包含 `Form01` 与 `List01` 两个容器:列表模板 `Template01` 展示操作列(点击加号调用 `productForm.run('Form01','Template02','#ProductID#')`)以及连接查询得到的 `#ProductName#`、`#CategoryName#` 与 `#SupplierName#`;编辑表单 `Template02` 包含 `ProductName`、`Unit`、`Price` 三个文本输入框,以及两个借助自定义属性 `data-appmlapplication` 动态填充选项的下拉选择框——`select#SupplierID` 绑定 `Models/Dropdown_Suppliers`,`select#CategoryID` 绑定 `Models/Dropdown_Categories`。

外键下拉模型机制与源码静态核对

当 `productForm` 加载某条商品记录时,控制器除了回填普通输入框,还会分别请求两个下拉模型获取供应商与分类的键值列表,并以商品当前的 `SupplierID` 和 `CategoryID` 选中对应 `<option>`。这种“列表展示名称、表单提交外键 ID”的模式保证了关系型数据库的参照完整性。源页面共登记 8 个静态嵌入元素(操作单元格 `td`、3 个 `<input>`、2 个 `<select>` 与 2 个 `<script>`),均仅作静态审查而不执行来源脚本。

静态检查源代码同样发现一处标识符粘连笔误:原片段中的 `var products,productFormproducts=new AppML(...)` 缺少分号/换行,应修正为 `var products, productForm; products = new AppML("appml.php", "Models/Products");`。本站离线实测在 SQLite 中启用 `PRAGMA foreign_keys = ON`,验证了三表连接列表渲染、两个下拉模型选项绑定与默认选中状态、非法外键 `SupplierID=999` 被数据库完整性约束拦截、合法更新生效,以及本地回环 HTTP 同时提供商品与双下拉模型 JSON 接口。

Products 列表模板(Template01)连接字段核对

编辑列商品名称分类名称供应商名称
点击图标触发 productForm.run('Form01','Template02','#ProductID#')#ProductName##CategoryName##SupplierName#

运行 Products 三表连接列表、外键下拉模型、SQLite 外键校验更新与回环 HTTP 实测

含完整源码 · 215 行
展开查看收起
python
"""Offline CPython 3.12.14 verifier for AppML Ch11 (case-products)."""
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 Request, urlopen


def init_db() -> sqlite3.Connection:
    conn = sqlite3.connect(":memory:", check_same_thread=False)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA foreign_keys = ON")
    conn.execute("CREATE TABLE Categories (CategoryID INTEGER PRIMARY KEY, CategoryName TEXT NOT NULL)")
    conn.execute("CREATE TABLE Suppliers (SupplierID INTEGER PRIMARY KEY, SupplierName TEXT NOT NULL)")
    conn.execute(
        "CREATE TABLE Products ("
        "ProductID INTEGER PRIMARY KEY, ProductName TEXT NOT NULL, "
        "SupplierID INTEGER NOT NULL REFERENCES Suppliers(SupplierID), "
        "CategoryID INTEGER NOT NULL REFERENCES Categories(CategoryID), "
        "Unit TEXT NOT NULL, Price REAL NOT NULL)"
    )
    conn.executemany("INSERT INTO Categories VALUES (?, ?)", [
        (1, "Beverages"),
        (2, "Condiments"),
        (8, "Seafood"),
    ])
    conn.executemany("INSERT INTO Suppliers VALUES (?, ?)", [
        (1, "Exotic Liquid"),
        (2, "New Orleans Cajun Delights"),
        (4, "Tokyo Traders"),
    ])
    conn.executemany("INSERT INTO Products VALUES (?, ?, ?, ?, ?, ?)", [
        (1, "Chai", 1, 1, "10 boxes x 20 bags", 18.0),
        (2, "Aniseed Syrup", 1, 2, "12 - 550 ml bottles", 10.0),
        (3, "Ikura", 4, 8, "12 - 200 ml jars", 31.0),
    ])
    conn.commit()
    return conn


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


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

    join_sql = (
        "SELECT p.ProductID, p.ProductName, c.CategoryName, s.SupplierName, p.Unit, p.Price, p.SupplierID, p.CategoryID "
        "FROM Products p "
        "JOIN Categories c ON p.CategoryID = c.CategoryID "
        "JOIN Suppliers s ON p.SupplierID = s.SupplierID "
        "ORDER BY p.ProductID"
    )

    # Case 1: Template01 joined Products list rendering
    tpl1 = (
        '<tr id="appml_row">'
        '<td onclick="productForm.run(\'Form01\',\'Template02\',\'#ProductID#\')">+</td>'
        '<td>#ProductName#</td><td>#CategoryName#</td><td>#SupplierName#</td></tr>'
    )
    products = [dict(r) for r in db.execute(join_sql).fetchall()]
    rendered1 = [bind_hash(tpl1, p) for p in products]
    actual1 = {
        "product_count": len(rendered1),
        "first_row_has_join": "<td>Chai</td><td>Beverages</td><td>Exotic Liquid</td>" in rendered1[0],
        "first_row_has_trigger": "productForm.run('Form01','Template02','1')" in rendered1[0],
    }
    expected1 = {"product_count": 3, "first_row_has_join": True, "first_row_has_trigger": True}
    cases.append({
        "name": "products_joined_list_template",
        "summary": "Join Products with Categories and Suppliers and render Template01 list rows.",
        "expected": expected1,
        "actual": actual1,
        "passed": actual1 == expected1,
    })

    # Case 2: Resolve data-appmlapplication dropdown models (Suppliers & Categories)
    suppliers = [dict(r) for r in db.execute("SELECT SupplierID, SupplierName FROM Suppliers ORDER BY SupplierID").fetchall()]
    categories = [dict(r) for r in db.execute("SELECT CategoryID, CategoryName FROM Categories ORDER BY CategoryID").fetchall()]
    selected_product = products[0]
    sup_options = [
        f'<option value="{s["SupplierID"]}"{" selected" if s["SupplierID"] == selected_product["SupplierID"] else ""}>{escape(s["SupplierName"])}</option>'
        for s in suppliers
    ]
    cat_options = [
        f'<option value="{c["CategoryID"]}"{" selected" if c["CategoryID"] == selected_product["CategoryID"] else ""}>{escape(c["CategoryName"])}</option>'
        for c in categories
    ]
    actual2 = {
        "supplier_options_count": len(sup_options),
        "category_options_count": len(cat_options),
        "selected_supplier_option": next(o for o in sup_options if " selected" in o),
        "selected_category_option": next(o for o in cat_options if " selected" in o),
    }
    expected2 = {
        "supplier_options_count": 3,
        "category_options_count": 3,
        "selected_supplier_option": '<option value="1" selected>Exotic Liquid</option>',
        "selected_category_option": '<option value="1" selected>Beverages</option>',
    }
    cases.append({
        "name": "dropdown_foreign_key_models",
        "summary": "Populate SupplierID and CategoryID <select> controls from Dropdown_Suppliers and Dropdown_Categories models.",
        "expected": expected2,
        "actual": actual2,
        "passed": actual2 == expected2,
    })

    # Case 3: Form UPDATE with foreign key integrity enforcement
    fk_rejected = False
    try:
        db.execute("UPDATE Products SET SupplierID = ? WHERE ProductID = ?", (999, 1))
        db.commit()
    except sqlite3.IntegrityError:
        fk_rejected = True
        db.rollback()
    db.execute(
        "UPDATE Products SET SupplierID = ?, CategoryID = ?, Price = ? WHERE ProductID = ?",
        (2, 2, 19.5, 1),
    )
    db.commit()
    updated = dict(db.execute(join_sql).fetchall()[0])
    actual3 = {
        "invalid_fk_rejected": fk_rejected,
        "updated_supplier": updated["SupplierName"],
        "updated_category": updated["CategoryName"],
        "updated_price": updated["Price"],
    }
    expected3 = {
        "invalid_fk_rejected": True,
        "updated_supplier": "New Orleans Cajun Delights",
        "updated_category": "Condiments",
        "updated_price": 19.5,
    }
    cases.append({
        "name": "products_form_update_fk_validation",
        "summary": "Enforce SQLite foreign key constraints when updating Products SupplierID, CategoryID, and Price.",
        "expected": expected3,
        "actual": actual3,
        "passed": actual3 == expected3,
    })

    # Case 4: Static JS fix check (without executing source scripts) + HTTP Products & Dropdown API
    fixed_js = 'var products, productForm;\nproducts = new AppML("appml.php", "Models/Products");'

    class ProdHandler(BaseHTTPRequestHandler):
        def do_GET(self):
            model = parse_qs(urlparse(self.path).query).get("model", [""])[0]
            if model == "Models/Products":
                data = {"records": [dict(r) for r in db.execute(join_sql).fetchall()]}
            elif model == "Models/Dropdown_Suppliers":
                data = {"records": [dict(r) for r in db.execute("SELECT SupplierID, SupplierName FROM Suppliers ORDER BY SupplierID").fetchall()]}
            elif model == "Models/Dropdown_Categories":
                data = {"records": [dict(r) for r in db.execute("SELECT CategoryID, CategoryName FROM Categories ORDER BY CategoryID").fetchall()]}
            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(json.dumps(data, ensure_ascii=False).encode("utf-8"))

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

    srv = HTTPServer(("127.0.0.1", 0), ProdHandler)
    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/Products", timeout=5) as r:
            p_recs = json.loads(r.read().decode("utf-8"))["records"]
        with urlopen(f"http://127.0.0.1:{port}/appml.php?model=Models/Dropdown_Suppliers", timeout=5) as r:
            s_recs = json.loads(r.read().decode("utf-8"))["records"]
        with urlopen(f"http://127.0.0.1:{port}/appml.php?model=Models/Dropdown_Categories", timeout=5) as r:
            c_recs = json.loads(r.read().decode("utf-8"))["records"]
    finally:
        srv.shutdown()
        srv.server_close()
        db.close()

    actual4 = {
        "products_count": len(p_recs),
        "suppliers_count": len(s_recs),
        "categories_count": len(c_recs),
        "js_typo_fixed": "productForm;" in fixed_js and "productFormproducts" not in fixed_js,
    }
    expected4 = {"products_count": 3, "suppliers_count": 3, "categories_count": 3, "js_typo_fixed": True}
    cases.append({
        "name": "products_static_code_and_http_api",
        "summary": "Serve Products and both dropdown models over local HTTP and statically verify corrected JS 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()
验证 Products 连接 Categories/Suppliers 渲染 3 行,Dropdown_Suppliers/Categories 生成带 selected 的选项,非法外键 SupplierID=999 被拒绝且合法更新生效,回环 HTTP 三个模型接口均正常返回。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a3200.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:AppML

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

下载课程关联工程包:AppML

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

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

列表面向阅读需要展示易懂的分类和供应商名称(通过表连接获取),而数据库 Products 表存储的是规范化外键 ID;下拉框以名称展示给用户、以 ID 提交回后端,配合外键约束可防止产生孤立脏数据。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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