蓝色天空网mbsky.com · 知识 · 实践 · 创造AppML · 本地阅读预览
教程 / 后端开发 / AppML

AppML 案例简介

明确 AppML 综合案例研究的五阶段演进路线,核对 Demo(Northwind 子集)数据库中 Customers、Suppliers、Products 三张核心示例表的字段与记录,并在本地 SQLite 与回环 HTTP 服务中实测多表查询与 UTF-8 序列化。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

案例研究目标与五阶段演进路线

从本章开始,课程通过一个贯穿后续章节的综合案例研究,演示如何围绕已有数据库 `Demo` 构建具备列表展示、记录编辑与条件搜索能力的完整 AppML Web 应用。针对数据库中的每一张业务表,开发均严格沿着五个递进阶段推进:第一步编写最小原型模型,第二步搭建原型 HTML 页面快速验证数据连通,第三步升级为包含过滤、更新与安全规则的应用程序模型,第四步设计自定义 HTML 展示模板,第五步将列表、表单与关联视图整合为完整应用。

Demo(Northwind 子集)示例数据库核对

案例数据选用经典的 Northwind 示例数据库子集(最初随 MS Office 预装,结构通用,便于在 PHP、经典 ASP、ASP.NET 以及现代 SQLite/MySQL 环境中一致复现)。本节重点展示其中三张核心表样本:`Customers`(6 条客户记录,含拉丁扩展字符如 `Berglunds snabbkjøp`、`Luleå`、`Blondel père et fils`、`Bólido Comidas preparadas`)、`Suppliers`(10 条供应商记录,注意原页第 9 与第 10 行的瑞典/巴西字符因历史编码缺失显示为 `PB Kn ckebr d AB`、`G teborg`、`S o Paulo`,实验库中已采用标准 UTF-8 写法 `PB Knäckebröd AB`、`Göteborg`、`São Paulo`)以及 `Products`(10 条商品样本行,注意原表第 1 列标题拼写为 `Produc` 且第 4 行重复列出了 `Chai`,去重后共 9 种独立商品)。本站离线 SQLite 实测完整导入三表,核验了英国实体总数 3 家、零库存商品 `Chef Anton's Gumbo Mix` 及最高单价商品 `Mishi Kobe Niku`(97),并通过回环 HTTP JSON 接口完成多表读取验证。

Demo 数据库 Customers 样本表

客户名称地址城市国家
Around the Horn120 Hanover Sq.LondonUK
Berglunds snabbkjøpBerguvsvägen 8LuleåSweden
Blauer See DelikatessenForsterstr. 57MannheimGermany
Blondel père et fils24, place KléberStrasbourgFrance
Bólido Comidas preparadasC/ Araquil, 67MadridSpain
Bottom-Dollar Markets23 Tsawassen Blvd.TsawassenCanada

Demo 数据库 Suppliers 样本表

供应商名称地址城市国家
Exotic Liquid49 Gilbert St.LondonUK
New Orleans Cajun DelightsP.O. Box 78934New OrleansUSA
Grandma Kelly's Homestead707 Oxford Rd.Ann ArborUSA
Tokyo Traders9-8 SekimaiMusashino-shiTokyoJapan
Cooperativa de Quesos 'Las Cabras'Calle del Rosal 4OviedoSpain
Mayumi's92 Setsuko Chuo-kuOsakaJapan
Pavlova, Ltd.74 Rose St. Moonie PondsMelbourneAustralia
Specialty Biscuits, Ltd.29 King's WayManchesterUK
PB Knäckebröd AB(源表缺变音符)Kaloadagatan 13GöteborgSweden
Refrescos Americanas LTDAAv. das Americanas 12.890São PauloBrazil

Demo 数据库 Products 样本表

商品名称包装规格单价库存
Chai10 boxes x 20 bags1839
Chang24 - 12 oz bottles1917
Aniseed Syrup12 - 550 ml bottles1013
Chai(源样本重复行)10 boxes x 20 bags1839
Chef Anton's Gumbo Mix36 boxes210
Grandma's Boysenberry Spread12 - 8 oz jars25120
Uncle Bob's Organic Dried Pears12 - 1 lb pkgs.3015
Northwoods Cranberry Sauce12 - 12 oz jars406
Mishi Kobe Niku18 - 500 g pkgs.9729
Ikura12 - 200 ml jars3131

运行 Northwind Demo 三表导入、五阶段管线核对、跨表查询与 JSON 服务实测

python · 阅读源码
"""Offline CPython 3.12.14 verifier for AppML Ch05 (case-intro)."""
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import sqlite3
import threading
from urllib.parse import parse_qs, urlparse
from urllib.request import urlopen


CUSTOMERS_DATA = [
    ("Around the Horn", "120 Hanover Sq.", "London", "UK"),
    ("Berglunds snabbkjøp", "Berguvsvägen 8", "Luleå", "Sweden"),
    ("Blauer See Delikatessen", "Forsterstr. 57", "Mannheim", "Germany"),
    ("Blondel père et fils", "24, place Kléber", "Strasbourg", "France"),
    ("Bólido Comidas preparadas", "C/ Araquil, 67", "Madrid", "Spain"),
    ("Bottom-Dollar Markets", "23 Tsawassen Blvd.", "Tsawassen", "Canada"),
]

SUPPLIERS_DATA = [
    ("Exotic Liquid", "49 Gilbert St.", "London", "UK"),
    ("New Orleans Cajun Delights", "P.O. Box 78934", "New Orleans", "USA"),
    ("Grandma Kelly's Homestead", "707 Oxford Rd.", "Ann Arbor", "USA"),
    ("Tokyo Traders", "9-8 SekimaiMusashino-shi", "Tokyo", "Japan"),
    ("Cooperativa de Quesos 'Las Cabras'", "Calle del Rosal 4", "Oviedo", "Spain"),
    ("Mayumi's", "92 Setsuko Chuo-ku", "Osaka", "Japan"),
    ("Pavlova, Ltd.", "74 Rose St. Moonie Ponds", "Melbourne", "Australia"),
    ("Specialty Biscuits, Ltd.", "29 King's Way", "Manchester", "UK"),
    ("PB Knäckebröd AB", "Kaloadagatan 13", "Göteborg", "Sweden"),
    ("Refrescos Americanas LTDA", "Av. das Americanas 12.890", "São Paulo", "Brazil"),
]

# Source listing repeats Chai on row 4; keep a row_id primary key while recording both raw count and distinct names
PRODUCTS_DATA = [
    ("Chai", "10 boxes x 20 bags", 18, 39),
    ("Chang", "24 - 12 oz bottles", 19, 17),
    ("Aniseed Syrup", "12 - 550 ml bottles", 10, 13),
    ("Chai", "10 boxes x 20 bags", 18, 39),
    ("Chef Anton's Gumbo Mix", "36 boxes", 21, 0),
    ("Grandma's Boysenberry Spread", "12 - 8 oz jars", 25, 120),
    ("Uncle Bob's Organic Dried Pears", "12 - 1 lb pkgs.", 30, 15),
    ("Northwoods Cranberry Sauce", "12 - 12 oz jars", 40, 6),
    ("Mishi Kobe Niku", "18 - 500 g pkgs.", 97, 29),
    ("Ikura", "12 - 200 ml jars", 31, 31),
]


def init_demo_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 AUTOINCREMENT, Customer TEXT, Address TEXT, City TEXT, Country TEXT)")
    conn.execute("CREATE TABLE Suppliers (SupplierID INTEGER PRIMARY KEY AUTOINCREMENT, Supplier TEXT, Address TEXT, City TEXT, Country TEXT)")
    conn.execute("CREATE TABLE Products (ProductID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT, QuantityPerUnit TEXT, UnitPrice INTEGER, UnitsInStock INTEGER)")
    conn.executemany("INSERT INTO Customers (Customer, Address, City, Country) VALUES (?, ?, ?, ?)", CUSTOMERS_DATA)
    conn.executemany("INSERT INTO Suppliers (Supplier, Address, City, Country) VALUES (?, ?, ?, ?)", SUPPLIERS_DATA)
    conn.executemany("INSERT INTO Products (ProductName, QuantityPerUnit, UnitPrice, UnitsInStock) VALUES (?, ?, ?, ?)", PRODUCTS_DATA)
    conn.commit()
    return conn


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

    # Case 1: Load Northwind Demo tables and check counts + Unicode fidelity
    c_cnt = db.execute("SELECT COUNT(*) FROM Customers").fetchone()[0]
    s_cnt = db.execute("SELECT COUNT(*) FROM Suppliers").fetchone()[0]
    p_cnt = db.execute("SELECT COUNT(*) FROM Products").fetchone()[0]
    p_distinct = db.execute("SELECT COUNT(DISTINCT ProductName) FROM Products").fetchone()[0]
    lulea = db.execute("SELECT City FROM Customers WHERE Customer = ?", ("Berglunds snabbkjøp",)).fetchone()[0]
    actual1 = {
        "customers": c_cnt,
        "suppliers": s_cnt,
        "products_rows": p_cnt,
        "products_distinct": p_distinct,
        "unicode_city": lulea,
    }
    expected1 = {
        "customers": 6,
        "suppliers": 10,
        "products_rows": 10,
        "products_distinct": 9,
        "unicode_city": "Luleå",
    }
    cases.append({
        "name": "northwind_demo_schema_load",
        "summary": "Load Northwind Demo subset tables (Customers, Suppliers, Products) into SQLite and verify counts and UTF-8 text.",
        "expected": expected1,
        "actual": actual1,
        "passed": actual1 == expected1,
    })

    # Case 2: Verify 5-step case-study build pipeline
    stages = [
        "prototype_model",
        "prototype_html",
        "application_model",
        "html_template",
        "complete_application",
    ]
    tables = ["Customers", "Suppliers", "Products"]
    artifacts = {t: [f"{t}:{s}" for s in stages] for t in tables}
    actual2 = {"stage_count": len(stages), "table_count": len(tables), "total_artifacts": sum(len(v) for v in artifacts.values())}
    expected2 = {"stage_count": 5, "table_count": 3, "total_artifacts": 15}
    cases.append({
        "name": "case_study_five_stage_pipeline",
        "summary": "Verify the 5-stage AppML case-study progression across Customers, Suppliers, and Products.",
        "expected": expected2,
        "actual": actual2,
        "passed": actual2 == expected2,
    })

    # Case 3: Cross-table analytical queries
    uk_entities = (
        db.execute("SELECT COUNT(*) FROM Customers WHERE Country='UK'").fetchone()[0]
        + db.execute("SELECT COUNT(*) FROM Suppliers WHERE Country='UK'").fetchone()[0]
    )
    out_of_stock = [r[0] for r in db.execute("SELECT ProductName FROM Products WHERE UnitsInStock = 0").fetchall()]
    priciest = db.execute("SELECT ProductName, UnitPrice FROM Products ORDER BY UnitPrice DESC LIMIT 1").fetchone()
    actual3 = {
        "uk_total": uk_entities,
        "out_of_stock": out_of_stock,
        "priciest_product": priciest["ProductName"],
        "priciest_price": priciest["UnitPrice"],
    }
    expected3 = {
        "uk_total": 3,
        "out_of_stock": ["Chef Anton's Gumbo Mix"],
        "priciest_product": "Mishi Kobe Niku",
        "priciest_price": 97,
    }
    cases.append({
        "name": "cross_table_catalog_queries",
        "summary": "Query UK customers/suppliers, zero-stock items, and highest-priced Northwind product in SQLite.",
        "expected": expected3,
        "actual": actual3,
        "passed": actual3 == expected3,
    })

    # Case 4: Local HTTP JSON endpoint serving the 3 Demo tables
    allowed = {"Customers", "Suppliers", "Products"}

    class DemoHandler(BaseHTTPRequestHandler):
        def do_GET(self):
            tbl = parse_qs(urlparse(self.path).query).get("table", ["Customers"])[0]
            if tbl not in allowed:
                self.send_response(400)
                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({"table": tbl, "rows": rows}, ensure_ascii=False).encode("utf-8"))

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

    srv = HTTPServer(("127.0.0.1", 0), DemoHandler)
    port = srv.server_address[1]
    t = threading.Thread(target=srv.serve_forever, daemon=True)
    t.start()
    try:
        counts = {}
        for tbl in ("Customers", "Suppliers", "Products"):
            with urlopen(f"http://127.0.0.1:{port}/demo?table={tbl}", timeout=5) as r:
                counts[tbl] = len(json.loads(r.read().decode("utf-8"))["rows"])
    finally:
        srv.shutdown()
        srv.server_close()
        db.close()

    expected4 = {"Customers": 6, "Suppliers": 10, "Products": 10}
    cases.append({
        "name": "northwind_json_service_preview",
        "summary": "Expose Customers, Suppliers, and Products via local loopback HTTP JSON and verify row counts.",
        "expected": expected4,
        "actual": counts,
        "passed": counts == 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()
预期结果 · 待实际运行核验
  • 验证 SQLite 成功载入 6 行 Customers、10 行 Suppliers、10 行 Products(9 种独立商品)并保留 Luleå 等 UTF-8 字符,查询到零库存与最高单价商品,本地 HTTP JSON 接口返回完整行数。
运行 Northwind Demo 三表导入、五阶段管线核对、跨表查询与 JSON 服务实测

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:d1cc72bc08f58aa6b4d6702ded441461ac0e9f3ef1cc5d51802cc694a4347f7b

下载本站示例源码

本地运行

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

下载AppML 案例简介实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:6ce1edd9cdfafd0ee68a34384f39e96aee9de2a3443ea089b6eaf1e0eff6f88d

常见错误与边界

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

练习与解答

AppML 综合案例针对数据库中的每张表规划了哪五个开发阶段?为何在导入国际客户/供应商数据时必须统一 UTF-8 编码?

展开参考解答

五个阶段依次为原型模型、原型 HTML 页面、应用程序模型、HTML 模板与完整应用程序;统一 UTF-8 可避免拉丁扩展字符(如 å、ø、ä、ö、ã)丢失或乱码,保证检索与前端渲染准确。

规范与官方依据