"""Offline Playwright Chromium + loopback HTTP/SQLite lab for jQuery EasyUI Ch 23: DataGrid Search."""
import json
import sqlite3
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs
from playwright.sync_api import sync_playwright
SEED_ITEMS = [
("EST-1", "FI-SW-01", 16.5, 10.0, "Large", "P"),
("EST-10", "K9-DL-01", 18.5, 12.0, "Spotted Adult Female", "P"),
("EST-11", "RP-SN-01", 28.5, 12.0, "Venomless", "P"),
("EST-12", "RP-SN-01", 26.5, 12.0, "Rattleless", "P"),
("EST-13", "RP-LI-02", 18.5, 12.0, "Green Adult", "P"),
("EST-14", "FL-DSH-01", 58.5, 12.0, "Tailless", "P"),
("EST-15", "FL-DSH-01", 23.5, 12.0, "With tail", "P"),
("EST-16", "FL-DLH-02", 93.5, 12.0, "Adult Female", "P"),
("EST-17", "FL-DLH-02", 93.5, 12.0, "Adult Male", "P"),
("EST-18", "AV-CB-01", 193.5, 92.0, "Adult Male", "P"),
("EST-20", "FI-SW-02", 15.5, 9.0, "Small", "P"),
("EST-21", "K9-PO-02", 22.0, 14.0, "Male Puppy", "P"),
]
HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>EasyUI DataGrid Search Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 12px; }
.dg-panel { width: 640px; border: 1px solid #95b8e7; }
.dg-title { background: #e0ecff; padding: 6px 8px; font-weight: 600; font-size: 13px; border-bottom: 1px solid #95b8e7; }
#tb { padding: 5px; background: #f4f4f4; border-bottom: 1px solid #ddd; font-size: 12px; }
#tb input { line-height: 22px; border: 1px solid #ccc; width: 100px; margin-right: 8px; }
table { width: 100%; border-collapse: collapse; font-size: 12px; }
th, td { border: 1px solid #ddd; padding: 4px 6px; }
th { background: #efefef; }
.dg-pager { padding: 5px 8px; background: #f4f4f4; border-top: 1px solid #ddd; font-size: 12px; display: flex; gap: 8px; align-items: center; }
</style>
</head>
<body>
<div class="dg-panel">
<div class="dg-title">Load Data</div>
<div id="tb">
<span>Item ID:</span><input id="itemid">
<span>Product ID:</span><input id="productid">
<a href="#" id="btn-search" class="easyui-linkbutton" onclick="doSearch();return false;">Search</a>
</div>
<table id="tt">
<thead>
<tr>
<th width="30">#</th>
<th width="80">Item ID</th>
<th width="80">Product ID</th>
<th width="80" style="text-align:right">List Price</th>
<th width="80" style="text-align:right">Unit Cost</th>
<th width="150">Attribute</th>
<th width="60" style="text-align:center">Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
<div class="dg-pager">
<button id="btn-prev" type="button">Prev</button>
<button id="btn-next" type="button">Next</button>
<span id="pager-info"></span>
</div>
</div>
<script>
const state = { page: 1, rows: 5, queryParams: { itemid: '', productid: '' }, total: 0, data: [], lastPayload: null };
async function loadPage(pageNum, extraParams) {
if (extraParams) {
state.queryParams = { itemid: extraParams.itemid || '', productid: extraParams.productid || '' };
state.page = 1;
} else {
state.page = pageNum;
}
const params = new URLSearchParams({
page: String(state.page),
rows: String(state.rows),
itemid: state.queryParams.itemid,
productid: state.queryParams.productid,
});
state.lastPayload = Object.fromEntries(params.entries());
const resp = await fetch('/datagrid24_getdata', { method: 'POST', body: params });
const json = await resp.json();
state.total = json.total;
state.data = json.rows;
const tbody = document.querySelector('#tt tbody');
tbody.innerHTML = '';
const offset = (state.page - 1) * state.rows;
json.rows.forEach((r, idx) => {
const tr = document.createElement('tr');
tr.innerHTML = `<td>${offset + idx + 1}</td><td>${r.itemid}</td><td>${r.productid}</td><td style="text-align:right">${r.listprice}</td><td style="text-align:right">${r.unitcost}</td><td>${r.attr1}</td><td style="text-align:center">${r.status}</td>`;
tbody.appendChild(tr);
});
document.getElementById('pager-info').textContent = `Page ${state.page} / Total ${state.total}`;
window._loadDone = (window._loadDone || 0) + 1;
}
window.doSearch = function() {
loadPage(1, {
itemid: document.getElementById('itemid').value,
productid: document.getElementById('productid').value,
});
};
document.getElementById('btn-prev').addEventListener('click', () => {
if (state.page > 1) loadPage(state.page - 1);
});
document.getElementById('btn-next').addEventListener('click', () => {
if (state.page * state.rows < state.total) loadPage(state.page + 1);
});
window.gridState = () => ({
page: state.page,
total: state.total,
rowNumbers: Array.from(document.querySelectorAll('#tt tbody tr td:first-child')).map(td => parseInt(td.textContent, 10)),
itemids: state.data.map(r => r.itemid),
lastPayload: state.lastPayload,
});
loadPage(1);
</script>
</body>
</html>
"""
def start_server():
conn = sqlite3.connect(":memory:", check_same_thread=False)
conn.execute("CREATE TABLE item (itemid TEXT, productid TEXT, listprice REAL, unitcost REAL, attr1 TEXT, status TEXT)")
conn.executemany("INSERT INTO item VALUES (?, ?, ?, ?, ?, ?)", SEED_ITEMS)
conn.commit()
lock = threading.Lock()
class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
pass
def do_GET(self):
body = HTML_DOC.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
length = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(length).decode("utf-8")
qs = parse_qs(raw, keep_blank_values=True)
page = max(1, int(qs.get("page", ["1"])[0]))
rows = max(1, int(qs.get("rows", ["10"])[0]))
itemid = qs.get("itemid", [""])[0]
productid = qs.get("productid", [""])[0]
offset = (page - 1) * rows
with lock:
total = conn.execute(
"SELECT COUNT(*) FROM item WHERE itemid LIKE ? AND productid LIKE ?",
(itemid + "%", productid + "%"),
).fetchone()[0]
cur = conn.execute(
"SELECT itemid, productid, listprice, unitcost, attr1, status FROM item "
"WHERE itemid LIKE ? AND productid LIKE ? LIMIT ? OFFSET ?",
(itemid + "%", productid + "%", rows, offset),
)
items = [
dict(itemid=r[0], productid=r[1], listprice=r[2], unitcost=r[3], attr1=r[4], status=r[5])
for r in cur.fetchall()
]
payload = json.dumps({"total": total, "rows": items}).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
srv = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
return srv, conn
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
srv, conn = start_server()
port = srv.server_address[1]
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 760, "height": 480})
page.goto(f"http://127.0.0.1:{port}/")
page.wait_for_function("() => window._loadDone >= 1")
# Case 1: Initial paginated load from loopback HTTP/SQLite endpoint
res1 = page.evaluate("() => window.gridState()")
exp1 = {
"page": 1,
"total": 12,
"rowNumbers": [1, 2, 3, 4, 5],
"itemids": ["EST-1", "EST-10", "EST-11", "EST-12", "EST-13"],
"lastPayload": {"page": "1", "rows": "5", "itemid": "", "productid": ""},
}
cases.append(dict(name="initial_paginated_load_from_loopback", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Toolbar search by itemid and productid prefix via doSearch -> load
page.fill("#itemid", "EST-1")
page.fill("#productid", "RP-SN")
page.click("#btn-search")
page.wait_for_function("() => window._loadDone >= 2")
res2 = page.evaluate("() => window.gridState()")
exp2 = {
"page": 1,
"total": 2,
"rowNumbers": [1, 2],
"itemids": ["EST-11", "EST-12"],
"lastPayload": {"page": "1", "rows": "5", "itemid": "EST-1", "productid": "RP-SN"},
}
cases.append(dict(name="toolbar_search_by_itemid_and_productid", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Reset inputs -> page 2 -> empty search resets page to 1
page.fill("#itemid", "")
page.fill("#productid", "")
page.click("#btn-search")
page.wait_for_function("() => window._loadDone >= 3")
page.click("#btn-next")
page.wait_for_function("() => window._loadDone >= 4")
page2_state = page.evaluate("() => ({ page: window.gridState().page, rowNumbers: window.gridState().rowNumbers })")
page.fill("#itemid", "NOPE")
page.click("#btn-search")
page.wait_for_function("() => window._loadDone >= 5")
empty_state = page.evaluate("() => window.gridState()")
res3 = {
"page2BeforeEmpty": page2_state,
"emptyPage": empty_state["page"],
"emptyTotal": empty_state["total"],
"emptyItemIds": empty_state["itemids"],
}
exp3 = {
"page2BeforeEmpty": {"page": 2, "rowNumbers": [6, 7, 8, 9, 10]},
"emptyPage": 1,
"emptyTotal": 0,
"emptyItemIds": [],
}
cases.append(dict(name="search_resets_page_and_handles_empty_match", expected=exp3, actual=res3, passed=(res3 == exp3)))
browser.close()
finally:
srv.shutdown()
conn.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/jeasyui-datagrid-datagrid24-lab/explore-datagrid-datagrid24.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-datagrid-datagrid24.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a981.zip