如何使用 AppML
分四步拆解创建 AppML 应用的完整流程:编写含排序与过滤器的 XML 模型、渐进搭建 HTML 页面与样式、通过 appml.js 驱动模板渲染,并核对运行机制、标准目录布局与扩展边界。
学完这一章,你能够
- 分四步拆解创建 AppML 应用的完整流程:编写含排序与过滤器的 XML 模型、渐进搭建 HTML 页面与样式、通过 appml.js 驱动模板渲染,并核对运行机制、标准目录布局与扩展边界。
四步构建流程与 XML 模型解析
创建一个可运行的 AppML 应用遵循四个循序渐进的步骤:先定义 XML 数据模型,再搭建基础 HTML 结构,接着引入样式表美化排版,最后接入脚本执行数据绑定(具体环境下载与部署配置将在下一章展开)。第一步需在推荐的 `Models` 子目录下新建 `Customers.xml`,在其中声明数据库连接、查询语句、默认排序和过滤字段。
`Customers.xml` 由七个核心标签层级组成:根元素 `<appml>` 定义模型边界;`<datasource>` 声明数据源容器;`<database>` 指明关系型数据库类型;`<connection>` 绑定配置中的连接名(如 `Demo`);`<sql>` 写入基础 `SELECT` 查询;`<orderby>` 设定默认排序字段(如 `CustomerName`);`<filters>` 内的 `<query>` 则声明允许客户端筛选的合法字段白名单(如 `CustomerName`)。本站实测使用 ElementTree 核验了全部标签层级,并在 SQLite 中结合 `ORDER BY CustomerName` 与参数化 `WHERE CustomerName LIKE ?` 验证排序与安全过滤。
渐进构建 HTML 视图、样式与执行脚本
前端页面采用渐进增强方式演进:第二步先编写包含表头与单条静态客户记录的普通 HTML `<table>` 验证结构;第三步在 `<head>` 中引入 `<link rel="stylesheet" href="appml.css">` 并给表格加上 `class="appmltable"` 呈现规范样式;第四步用 `<div id="Place01">` 包裹 `<table id="Template01">`,将静态数据行替换为带 `id="appml_row"` 与 `#CustomerName#`、`#City#`、`#Country#` 占位符的模板行,再引入 `<script src="appml.js"></script>` 并执行 `app = new AppML("appml.htmlx", "Models/Customers.xml"); app.run("Place01", "Template01");`。
上述脚本的核心工作机制十分清晰:`<script src="appml.js">` 载入客户端控制器函数库;`new AppML("appml.htmlx", "Models/Customers.xml")` 创建应用实例并指向服务端控制器脚本与模型路径;`app.run("Place01", "Template01")` 指定输出目标容器为 `Place01`、渲染模板为 `Template01`;带有 `id="appml_row"` 的元素会在每条记录返回时被复制一次,其中被 `#...#` 包裹的标记将自动替换为模型字段值(现代开发中需同时对替换值做 HTML 转义以防 XSS,本站实测已强制启用 `html.escape`)。
运行机制、目录结构与自由扩展能力
完整运行时序分为读与写两个阶段:页面加载后载入浏览器端 AppML 控制器并实例化对象;调用运行方法时,客户端向服务端数据控制器发起请求,服务端依据 XML 模型读取数据并回传,客户端再按模板或自定义代码渲染界面。若业务开启编辑能力,用户可在页面修改数据,由客户端在后台提交至服务端控制器完成校验与持久化落库。本站实测通过本地 HTTP `GET` 与 `POST` 完整验证了读取与更新落库闭环。
典型的 AppML 站点目录保持扁平清晰:根目录如 `Demo` 下分设 `Data`(数据文件)、`Images`(图片资源)、`Models`(XML 模型)三个子目录,同级放置业务页面 `Demo.htm` 与样式 `Demo.css`,以及框架核心文件 `appml_config.php`(或 `.htmlx` 配置)、`appml.css`、`appml.js` 与服务端控制器 `appml.php`(或 `.htmlx`)。
AppML 对象可嵌入任意 HTML 页面且不干扰其他区域:当未提供模板时会自动渲染默认列表以便快速原型验证;但它的核心定位在于数据供给与建模而非锁死 UI。开发者既可以自写 HTML 交由 AppML 填充数据,也可仅拉取模型数据后完全自控渲染,或组合调用其属性与方法。在数据层,模型支持按用户/角色定义访问安全、对接 Access/MySQL/SQL Server/Oracle 等关系型数据库以及 XML/文本数据源、声明数据类型/格式/约束并扩展自定义节点(详细标签规范可参阅参考手册)。需要提醒的是,若将类似能力迁移到现代工程,应采用参数化 SQL 与前后端 JSON API。
典型 AppML Web 目录与文件清单
| 分类 | 标准目录与文件 |
| 业务目录、应用文件与框架核心脚本 | 目录含 Demo/Data/Images/Models;业务文件含 Demo.htm 与 Demo.css;框架文件含 appml_config.php(.htmlx)、appml.css、appml.js 与 appml.php(.htmlx)。 |
运行 AppML 四步建模、ORDER BY/过滤查询、模板展开与目录控制器实测
展开查看收起
"""Offline CPython 3.12.14 verifier for AppML Ch02 (howto)."""
from html import escape
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import re
import sqlite3
import threading
from urllib.request import Request, urlopen
import xml.etree.ElementTree as ET
CUSTOMERS_XML = """<appml>
<datasource>
<database>
<connection>Demo</connection>
<sql>SELECT CustomerName,ContactName,City,Country FROM Customers</sql>
<orderby>CustomerName</orderby>
</database>
</datasource>
<filters>
<query>
<field>CustomerName</field>
</query>
</filters>
</appml>"""
SEED_ROWS = [
(1, "Bottom-Dollar Markets", "Elizabeth Lincoln", "Tsawassen", "Canada"),
(2, "Alfreds Futterkiste", "Maria Anders", "Berlin", "Germany"),
(3, "Around the Horn", "Thomas Hardy", "London", "UK"),
(4, "Ana Trujillo Emparedados", "Ana Trujillo", "México D.F.", "Mexico"),
]
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 NOT NULL, "
"ContactName TEXT NOT NULL, "
"City TEXT NOT NULL, "
"Country TEXT NOT NULL)"
)
conn.executemany(
"INSERT INTO Customers VALUES (?, ?, ?, ?, ?)",
SEED_ROWS,
)
conn.commit()
return conn
def run_cases() -> list[dict]:
cases = []
# Case 1: Validate all 7 XML model tags
root = ET.fromstring(CUSTOMERS_XML)
tag_set = sorted({elem.tag for elem in root.iter()})
orderby = (root.findtext("./datasource/database/orderby") or "").strip()
filter_fields = [e.text.strip() for e in root.findall("./filters/query/field") if e.text]
actual1 = {
"tags": tag_set,
"connection": (root.findtext("./datasource/database/connection") or "").strip(),
"orderby": orderby,
"filter_fields": filter_fields,
}
expected1 = {
"tags": ["appml", "connection", "database", "datasource", "field", "filters", "orderby", "query", "sql"],
"connection": "Demo",
"orderby": "CustomerName",
"filter_fields": ["CustomerName"],
}
cases.append({
"name": "model_with_orderby_and_filters",
"summary": "Parse Customers.xml and verify datasource, database, orderby, and query filter declarations.",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: Progressive HTML -> CSS -> Script template structure check
step2_html = "<table><tr><th>Customer</th><th>City</th><th>Country</th></tr><tr><td>Alfreds Futterkiste</td><td>Berlin</td><td>Germany</td></tr></table>"
step3_html = '<link rel="stylesheet" href="appml.css"><table class="appmltable"><tr><th>Customer</th></tr></table>'
step4_html = '<div id="Place01"><table id="Template01" class="appmltable"><tr id="appml_row"><td>#CustomerName#</td><td>#City#</td><td>#Country#</td></tr></table></div>'
actual2 = {
"step2_plain_table": "<table" in step2_html and "appmltable" not in step2_html,
"step3_styled_table": 'href="appml.css"' in step3_html and 'class="appmltable"' in step3_html,
"step4_placeholders": re.findall(r"#([A-Za-z0-9_]+)#", step4_html),
"step4_has_hooks": 'id="Place01"' in step4_html and 'id="Template01"' in step4_html and 'id="appml_row"' in step4_html,
}
expected2 = {
"step2_plain_table": True,
"step3_styled_table": True,
"step4_placeholders": ["CustomerName", "City", "Country"],
"step4_has_hooks": True,
}
cases.append({
"name": "static_html_and_css_stages",
"summary": "Verify progressive steps from static HTML table to appml.css styling and Template01 hooks.",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: SQLite orderby + parameterized filter + template rendering
db = init_db()
base_sql = (root.findtext("./datasource/database/sql") or "").strip()
all_ordered = [dict(r) for r in db.execute(f"{base_sql} ORDER BY {orderby}").fetchall()]
filtered = [
dict(r)
for r in db.execute(
f"{base_sql} WHERE CustomerName LIKE ? ORDER BY {orderby}",
("A%",),
).fetchall()
]
tpl = '<tr id="appml_row"><td>#CustomerName#</td><td>#City#</td><td>#Country#</td></tr>'
rendered = [
re.sub(r"#([A-Za-z0-9_]+)#", lambda m: escape(str(row[m.group(1)])), tpl)
for row in filtered
]
actual3 = {
"ordered_names": [r["CustomerName"] for r in all_ordered],
"filtered_a_count": len(filtered),
"first_rendered_row": rendered[0],
}
expected3 = {
"ordered_names": [
"Alfreds Futterkiste",
"Ana Trujillo Emparedados",
"Around the Horn",
"Bottom-Dollar Markets",
],
"filtered_a_count": 3,
"first_rendered_row": '<tr id="appml_row"><td>Alfreds Futterkiste</td><td>Berlin</td><td>Germany</td></tr>',
}
cases.append({
"name": "run_template_binding_and_filter",
"summary": "Execute ORDER BY CustomerName and parameterized filter in SQLite, then expand #Field# row template.",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: Standard folder layout + local HTTP controller GET/POST cycle
layout = {
"folders": ["Demo", "Data", "Images", "Models"],
"app_files": ["Demo.htm", "Demo.css"],
"framework_files": ["appml_config.php", "appml.css", "appml.js", "appml.php"],
}
class Controller(BaseHTTPRequestHandler):
def do_GET(self):
rows = [dict(r) for r in db.execute("SELECT CustomerName, City, Country FROM Customers ORDER BY CustomerName").fetchall()]
body = json.dumps({"records": rows}, ensure_ascii=False).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.end_headers()
self.wfile.write(body)
def do_POST(self):
length = int(self.headers.get("Content-Length", "0"))
data = json.loads(self.rfile.read(length).decode("utf-8"))
db.execute(
"UPDATE Customers SET City = ? WHERE CustomerName = ?",
(data["City"], data["CustomerName"]),
)
db.commit()
resp = json.dumps({"updated": True, "City": data["City"]}).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.end_headers()
self.wfile.write(resp)
def log_message(self, format, *args):
return
server = HTTPServer(("127.0.0.1", 0), Controller)
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.php?model=Models/Customers.xml", timeout=5) as r:
initial_count = len(json.loads(r.read().decode("utf-8"))["records"])
req = Request(
f"http://127.0.0.1:{port}/appml.php?model=Models/Customers.xml",
data=json.dumps({"CustomerName": "Alfreds Futterkiste", "City": "Hamburg"}).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
with urlopen(req, timeout=5) as r:
post_res = json.loads(r.read().decode("utf-8"))
with urlopen(f"http://127.0.0.1:{port}/appml.php?model=Models/Customers.xml", timeout=5) as r:
after_rows = json.loads(r.read().decode("utf-8"))["records"]
updated_city = next(x["City"] for x in after_rows if x["CustomerName"] == "Alfreds Futterkiste")
finally:
server.shutdown()
server.server_close()
db.close()
actual4 = {
"layout_item_count": len(layout["folders"]) + len(layout["app_files"]) + len(layout["framework_files"]),
"initial_count": initial_count,
"post_updated": post_res["updated"],
"persisted_city": updated_city,
}
expected4 = {
"layout_item_count": 10,
"initial_count": 4,
"post_updated": True,
"persisted_city": "Hamburg",
}
cases.append({
"name": "project_directory_and_controller_flow",
"summary": "Validate the 10-entry AppML project layout and round-trip GET/POST controller persistence.",
"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 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
第一个参数指定数据渲染后的挂载目标元素 ID,第二个参数指定用作渲染模板的隐藏元素 ID;若省略第二个参数,AppML 会依据模型字段自动生成默认的表格视图用于快速原型预览。