"""Offline ASP.NET semantic verification lab for Chapter 12 (webpages-webgrid)."""
import html
import json
import math
import sqlite3
VERSION = "CPython 3.12.14 offline ASP.NET WebPages/Core semantic verifier (IIS/WebMatrix absent)"
def build_small_bakery_db():
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
conn.execute("CREATE TABLE Product (Id INTEGER PRIMARY KEY, Name TEXT, Description TEXT, Price REAL)")
conn.executemany(
"INSERT INTO Product (Id, Name, Description, Price) VALUES (?, ?, ?, ?)",
[
(1, "Bread", "Baked fresh every day", 2.99),
(2, "Strawberry Shortcake", "A delicious treat", 9.99),
(3, "Apple Pie", "Classic cinnamon crust", 6.50),
(4, "Chocolate Muffin", "Rich dark cocoa", 3.25),
(5, "Croissant", "Flaky butter pastry", 2.50),
],
)
conn.commit()
return conn
def render_webgrid_html(rows, columns, sort_col=None, sort_dir="ASC", page=1, rows_per_page=3):
data = [dict(r) for r in rows]
if sort_col in columns:
data.sort(key=lambda r: r[sort_col], reverse=(sort_dir.upper() == "DESC"))
total_pages = max(1, math.ceil(len(data) / rows_per_page))
page = max(1, min(page, total_pages))
slice_rows = data[(page - 1) * rows_per_page : page * rows_per_page]
next_dir = "DESC" if sort_dir.upper() == "ASC" else "ASC"
ths = "".join(
f'<th scope="col"><a href="?sort={c}&sortdir={next_dir if c == sort_col else "ASC"}">{html.escape(c)}</a></th>'
for c in columns
)
trs = "".join(
"<tr>" + "".join(f"<td>{html.escape(str(r[c]))}</td>" for c in columns) + "</tr>"
for r in slice_rows
)
pager = " ".join(f'<a href="?page={p}">{p}</a>' if p != page else f"<span>{p}</span>" for p in range(1, total_pages + 1))
table_html = f"<table><thead><tr>{ths}</tr></thead><tfoot><tr><td colspan=\"{len(columns)}\">{pager}</td></tr></tfoot><tbody>{trs}</tbody></table>"
return {"html": table_html, "page": page, "total_pages": total_pages, "row_names": [r["Name"] for r in slice_rows]}
def case_manual_html_table_query():
conn = build_small_bakery_db()
rows = conn.execute("SELECT Id, Name, Description, Price FROM Product ORDER BY Name").fetchall()
body_rows = "".join(
f'<tr><td>{r["Id"]}</td><td>{html.escape(r["Name"])}</td><td>{html.escape(r["Description"])}</td><td align="right">{r["Price"]:.2f}</td></tr>'
for r in rows
)
expected = {
"row_count": 5,
"ordered_names": ["Apple Pie", "Bread", "Chocolate Muffin", "Croissant", "Strawberry Shortcake"],
"has_right_aligned_price": True,
}
actual = {
"row_count": len(rows),
"ordered_names": [r["Name"] for r in rows],
"has_right_aligned_price": '<td align="right">6.50</td>' in body_rows,
}
return {
"name": "manual_html_table_query",
"summary": "使用内存 SQLite SmallBakery 复现手写 <table> 与 foreach 按 Name 排序渲染商品表",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_webgrid_gethtml_default_order():
conn = build_small_bakery_db()
rows = conn.execute("SELECT Id, Name, Description, Price FROM Product ORDER BY Id").fetchall()
res = render_webgrid_html(rows, ["Id", "Name", "Description", "Price"], page=1, rows_per_page=10)
expected = {
"row_names": ["Bread", "Strawberry Shortcake", "Apple Pie", "Chocolate Muffin", "Croissant"],
"has_thead_and_tbody": True,
"sortable_headers_present": True,
}
actual = {
"row_names": res["row_names"],
"has_thead_and_tbody": "<thead>" in res["html"] and "<tbody>" in res["html"],
"sortable_headers_present": "?sort=Price&sortdir=ASC" in res["html"],
}
return {
"name": "webgrid_gethtml_default_order",
"summary": "模拟 new WebGrid(data).GetHtml() 自动生成带表头排序链接的 HTML 表格",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_webgrid_sorting_by_price_desc():
conn = build_small_bakery_db()
rows = conn.execute("SELECT Id, Name, Description, Price FROM Product ORDER BY Id").fetchall()
res = render_webgrid_html(rows, ["Id", "Name", "Description", "Price"], sort_col="Price", sort_dir="DESC", page=1, rows_per_page=3)
expected = {
"top3_names": ["Strawberry Shortcake", "Apple Pie", "Chocolate Muffin"],
"toggle_next_sort_asc": True,
}
actual = {
"top3_names": res["row_names"],
"toggle_next_sort_asc": "?sort=Price&sortdir=ASC" in res["html"],
}
return {
"name": "webgrid_sorting_by_price_desc",
"summary": "验证 WebGrid 点击列标题按 Price 降序排列并自动切换下一次排序方向为 ASC",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_webgrid_pagination_bounds():
conn = build_small_bakery_db()
rows = conn.execute("SELECT Id, Name, Description, Price FROM Product ORDER BY Id").fetchall()
p1 = render_webgrid_html(rows, ["Id", "Name", "Price"], page=1, rows_per_page=2)
p3 = render_webgrid_html(rows, ["Id", "Name", "Price"], page=3, rows_per_page=2)
expected = {
"total_pages": 3,
"page1_names": ["Bread", "Strawberry Shortcake"],
"page3_names": ["Croissant"],
"pager_has_page2_link": True,
}
actual = {
"total_pages": p1["total_pages"],
"page1_names": p1["row_names"],
"page3_names": p3["row_names"],
"pager_has_page2_link": '<a href="?page=2">2</a>' in p1["html"],
}
return {
"name": "webgrid_pagination_bounds",
"summary": "验证 WebGrid 分页切片计算、末页余数行展示与页脚分页链接生成",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_manual_html_table_query(),
case_webgrid_gethtml_default_order(),
case_webgrid_sorting_by_price_desc(),
case_webgrid_pagination_bounds(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 ASP.NET WebPages / Razor 语义验证器(本机未启动 IIS / IIS Express / WebMatrix 宿主环境)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 ASP.NET WebPages / Razor 语义验证器(本机未启动 IIS / IIS Express / WebMatrix 宿主环境)。
入口文件:projects/mvc-webpages-webgrid-lab/explore-webpages-webgrid.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-webpages-webgrid.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 ASP.NET WebPages / Razor 语义验证器(本机未启动 IIS / IIS Express / WebMatrix 宿主环境)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2903.zip
课程关联工程包(登记关联55章) · 含当前章节或实例 · mbskycom202612a2870.zip