AppML 教程
系统梳理 AppML(Application Modeling Language)的模型驱动定位、三层技术组成、最小 HTML+XML 工作流、现代架构特征与历史演进,并在本地 CPython/SQLite 环境中完成声明式模型解析与模板渲染实测。
学完这一章,你能够
- 系统梳理 AppML(Application Modeling Language)的模型驱动定位、三层技术组成、最小 HTML+XML 工作流、现代架构特征与历史演进,并在本地 CPython/SQLite 环境中完成声明式模型解析与模板渲染实测。
AppML 的定位与核心构成
AppML 全称 Application Modeling Language(应用建模语言),是一套面向 Web 应用程序的声明式 HTML 扩展框架,旨在以极低学习成本实现快速、简洁的数据驱动开发。它的运行链路清晰划分为三层:服务端使用 XML 文件声明应用模型与数据查询规则,客户端浏览器加载 JavaScript 控制器负责拉取与渲染数据,服务端则运行 PHP 或 ASP/ASP.NET 脚本完成数据库访问与写回。
该框架主打轻量上手体验:模型结构直观、扩展属性简明、无需复杂脚手架即可搭建原型,并且遵循标准 Web 技术,可在主流操作系统与浏览器环境中部署。需要明确历史背景:AppML 属于早期 Refsnes Data / W3Schools 教学型轻量框架,当代生产系统通常以 REST/JSON 接口搭配 Vue、React 或原生 Web Components 承担同等职责,学习 AppML 的核心价值在于理解声明式数据模型与前后端解耦思想。
HTML 视图与 XML 模型的最小闭环
构建最小 AppML 应用只需在 HTML 页面中引入 `appml.js`,并在服务端保存一份 XML 模型。页面内以 `id="Place01"` 作为挂载容器、`id="Template01"` 定义表格模板、`id="appml_row"` 标记重复行,并用 `#CustomerName#`、`#City#`、`#Country#` 占位符绑定字段;随后通过 `new AppML("appml.htmlx", "Models/Customers")` 与 `app.run("Place01", "Template01")` 驱动渲染。XML 模型则通过 `<appml><datasource><database>` 指定 `<connection>Demo</connection>` 与 `<sql>` 查询语句。对于熟悉 Web 基础或 PHP/ASP/ASP.NET 的开发者,这种将 SQL 逻辑与视图解耦的写法能直观减少样板代码。本站离线实测使用 `xml.etree.ElementTree` 解析该模型并在 SQLite 内存库中查询 3 条客户数据,确认 `#Field#` 占位符展开与现代 `{{Field}}` / `appml-repeat` 模板绑定结果完全等价。
架构特点与历史演进
在架构层面,AppML 围绕经典 MVC 分层组织代码:数据与页面展现彻底分离、仅在客户端与服务端之间传输结构化数据从而降低带宽占用,同时具备易于云端部署、快速迭代、高可扩展性与可测试性、配置灵活以及内建用户账号与角色权限支持等特点。本站实测通过本地回环 `http.server` 分别提供 JSON 数据接口与渲染后的 HTML 视图,复现了客户端与服务端分离的 MVC 通信过程。
回顾发展历程:1999 年 Refsnes Data 公司启动 AppML 研发,尝试以 XML 描述互联网应用;2000 年 9 月挪威手球联盟采用该方案将旧 DOS 信息系统迁移至 Web,据估算开发周期缩短约 75%;2007 年 9 月中旬一度因仅依赖经典 ASP 与 IE 而下线;2013 年 10 月重新以开源形式发布 PHP 与 ASP.NET 版本并兼容各主流浏览器。其 1999 年确立的七项初始目标——覆盖互联网运行、平台无关、坚持 HTTP/HTML/CSS/XML 标准、适应多样业务需求、具备自描述能力、易于开发维护以及面向未来演进——至今仍是现代 Web 架构设计的重要准则。
AppML 概览导语核对
| 主题 | 核心定位与现代对照 |
| 快速、简洁的声明式 Web 应用开发 | 以 XML 声明应用模型、以 HTML+JS 渲染视图,快速构建数据驱动应用;现代生产工程对应 REST/JSON 接口与 Vue/React/Web Components。 |
运行 AppML XML 模型解析、SQLite 查询、模板展开与本地 HTTP MVC 实测
展开查看收起
"""Offline CPython 3.12.14 verifier for AppML Ch01 (tutorial)."""
from html import escape
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import re
import sqlite3
import threading
from urllib.request import urlopen
import xml.etree.ElementTree as ET
MODEL_XML = """<appml>
<datasource>
<database>
<connection>Demo</connection>
<sql>SELECT CustomerName,City,Country FROM Customers</sql>
</database>
</datasource>
</appml>"""
TEMPLATE_ROW = (
'<tr id="appml_row"><td>#CustomerName#</td>'
'<td>#City#</td><td>#Country#</td></tr>'
)
SEED_CUSTOMERS = [
(1, "Alfreds Futterkiste", "Berlin", "Germany"),
(2, "Around the Horn", "London", "UK"),
(3, "Berglunds snabbkjøp", "Luleå", "Sweden"),
]
def init_db() -> sqlite3.Connection:
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
conn.execute(
"CREATE TABLE Customers ("
"CustomerID INTEGER PRIMARY KEY, "
"CustomerName TEXT NOT NULL, "
"City TEXT NOT NULL, "
"Country TEXT NOT NULL)"
)
conn.executemany(
"INSERT INTO Customers (CustomerID, CustomerName, City, Country) VALUES (?, ?, ?, ?)",
SEED_CUSTOMERS,
)
conn.commit()
return conn
def render_template(template: str, rows: list[dict], brace_style: str = "hash") -> list[str]:
pattern = re.compile(r"#([A-Za-z0-9_]+)#" if brace_style == "hash" else r"\{\{([A-Za-z0-9_]+)\}\}")
out = []
for row in rows:
out.append(pattern.sub(lambda m: escape(str(row[m.group(1)])), template))
return out
def run_cases() -> list[dict]:
cases = []
# Case 1: Parse XML model definition
root = ET.fromstring(MODEL_XML)
conn_name = (root.findtext("./datasource/database/connection") or "").strip()
sql_text = (root.findtext("./datasource/database/sql") or "").strip()
m = re.match(r"SELECT\s+(.+?)\s+FROM\s+(\w+)", sql_text, re.IGNORECASE)
cols = [c.strip() for c in m.group(1).split(",")] if m else []
table = m.group(2) if m else ""
actual1 = {"root": root.tag, "connection": conn_name, "table": table, "columns": cols}
expected1 = {
"root": "appml",
"connection": "Demo",
"table": "Customers",
"columns": ["CustomerName", "City", "Country"],
}
cases.append({
"name": "parse_appml_xml_model",
"summary": "Parse AppML XML model and extract connection, table, and projected columns.",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: Execute model SQL against in-memory SQLite
db = init_db()
rows = [dict(r) for r in db.execute(f"{sql_text} ORDER BY CustomerID").fetchall()]
actual2 = {
"row_count": len(rows),
"first_customer": rows[0]["CustomerName"],
"countries": [r["Country"] for r in rows],
}
expected2 = {
"row_count": 3,
"first_customer": "Alfreds Futterkiste",
"countries": ["Germany", "UK", "Sweden"],
}
cases.append({
"name": "sqlite_customers_query",
"summary": "Execute XML model SQL against local SQLite Customers table.",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: Render #Field# and modern {{Field}} template rows
rendered_hash = render_template(TEMPLATE_ROW, rows, brace_style="hash")
modern_tpl = TEMPLATE_ROW.replace("#CustomerName#", "{{CustomerName}}").replace("#City#", "{{City}}").replace("#Country#", "{{Country}}")
rendered_mustache = render_template(modern_tpl, rows, brace_style="mustache")
actual3 = {
"rendered_count": len(rendered_hash),
"first_row": rendered_hash[0],
"matches_modern_binding": rendered_hash == rendered_mustache,
}
expected3 = {
"rendered_count": 3,
"first_row": '<tr id="appml_row"><td>Alfreds Futterkiste</td><td>Berlin</td><td>Germany</td></tr>',
"matches_modern_binding": True,
}
cases.append({
"name": "render_appml_row_template",
"summary": "Expand #Field# placeholders in Template01 and verify parity with modern {{Field}} syntax.",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: Local HTTP MVC server serving JSON data and HTML view
payload_bytes = json.dumps({"model": "Models/Customers", "records": rows}, ensure_ascii=False).encode("utf-8")
html_bytes = (
"<!DOCTYPE html><html><body><h1>My First Web Application</h1>"
"<div id=\"Place01\"><table>" + "".join(rendered_hash) + "</table></div></body></html>"
).encode("utf-8")
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/appml?model=Customers":
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.end_headers()
self.wfile.write(payload_bytes)
else:
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(html_bytes)
def log_message(self, format, *args):
return
server = HTTPServer(("127.0.0.1", 0), Handler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
with urlopen(f"http://127.0.0.1:{port}/appml?model=Customers", timeout=5) as resp:
api_status = resp.status
api_data = json.loads(resp.read().decode("utf-8"))
with urlopen(f"http://127.0.0.1:{port}/index.html", timeout=5) as resp:
view_status = resp.status
view_html = resp.read().decode("utf-8")
finally:
server.shutdown()
server.server_close()
db.close()
actual4 = {
"api_status": api_status,
"view_status": view_status,
"api_record_count": len(api_data["records"]),
"view_has_first_customer": "Alfreds Futterkiste" in view_html,
}
expected4 = {
"api_status": 200,
"view_status": 200,
"api_record_count": 3,
"view_has_first_customer": True,
}
cases.append({
"name": "local_http_mvc_endpoint",
"summary": "Serve model JSON and rendered HTML view over local loopback HTTP to verify MVC separation.",
"expected": expected4,
"actual": actual4,
"passed": actual4 == expected4,
})
return cases
def main() -> None:
output = {
"version": "CPython 3.12.14 offline AppML model/template/SQLite verifier",
"cases": run_cases(),
}
print(json.dumps(output, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
AppML 由服务端 XML 模型、浏览器端 JavaScript 控制器以及服务端 PHP/ASP 数据控制器组成;现代应用通常用 OpenAPI/JSON Schema 与 REST/GraphQL 接口提供数据,并用 Vue、React 或原生 Web Components 完成客户端模板渲染。