"""Offline Playwright Chromium + SQLite HTTP verification lab for jEasyUI EDataGrid CRUD (Ch04)."""
import json
import sqlite3
import threading
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from playwright.sync_api import sync_playwright
DB_LOCK = threading.Lock()
def make_db():
conn = sqlite3.connect(":memory:", check_same_thread=False)
conn.row_factory = sqlite3.Row
conn.execute(
"CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT, phone TEXT, email TEXT)"
)
conn.executemany(
"INSERT INTO users(firstname, lastname, phone, email) VALUES (?, ?, ?, ?)",
[
("Tom", "Wu", "139-0001", "tom@example.com"),
("Mei", "Chen", "139-0002", "mei@example.com"),
],
)
conn.commit()
return conn
HTML_DOC = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jEasyUI Editable DataGrid Lab</title>
<style>
body { font-family: Arial, sans-serif; margin: 12px; }
#toolbar { background: #f4f4f4; padding: 6px; width: 538px; border: 1px solid #ccc; border-bottom: 0; }
#toolbar a { margin-right: 10px; cursor: pointer; text-decoration: none; color: #333; }
table.dg { width: 550px; border-collapse: collapse; }
table.dg th, table.dg td { border: 1px solid #ccc; padding: 4px 6px; font-size: 13px; }
table.dg tr.selected { background: #ffe48d; }
table.dg input { width: 92%; box-sizing: border-box; }
</style>
</head>
<body>
<div id="toolbar">
<a id="btn-new" href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="$('#dg').edatagrid('addRow')">New</a>
<a id="btn-destroy" href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="$('#dg').edatagrid('destroyRow')">Destroy</a>
<a id="btn-save" href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-save" plain="true" onclick="$('#dg').edatagrid('saveRow')">Save</a>
<a id="btn-cancel" href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-undo" plain="true" onclick="$('#dg').edatagrid('cancelRow')">Cancel</a>
</div>
<table id="dg" class="dg" title="My Users" toolbar="#toolbar" idField="id" rownumbers="true" fitColumns="true" singleSelect="true">
<thead>
<tr>
<th field="rn">#</th>
<th field="firstname" width="50" editor="{type:'validatebox',options:{required:true}}">First Name</th>
<th field="lastname" width="50" editor="{type:'validatebox',options:{required:true}}">Last Name</th>
<th field="phone" width="50" editor="text">Phone</th>
<th field="email" width="50" editor="{type:'validatebox',options:{validType:'email'}}">Email</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
const state = { opts: null, rows: [], selectedIndex: -1, editIndex: -1, backup: null };
function renderGrid() {
const tbody = document.querySelector('#dg tbody');
tbody.innerHTML = '';
state.rows.forEach((row, idx) => {
const tr = document.createElement('tr');
tr.dataset.idx = idx;
if (idx === state.selectedIndex) tr.classList.add('selected');
if (idx === state.editIndex) {
tr.classList.add('editing');
tr.innerHTML =
'<td>' + (idx + 1) + '</td>' +
'<td><input name="firstname" value="' + (row.firstname || '') + '"></td>' +
'<td><input name="lastname" value="' + (row.lastname || '') + '"></td>' +
'<td><input name="phone" value="' + (row.phone || '') + '"></td>' +
'<td><input name="email" value="' + (row.email || '') + '"></td>';
} else {
tr.innerHTML =
'<td>' + (idx + 1) + '</td>' +
'<td>' + (row.firstname || '') + '</td>' +
'<td>' + (row.lastname || '') + '</td>' +
'<td>' + (row.phone || '') + '</td>' +
'<td>' + (row.email || '') + '</td>';
}
tr.addEventListener('click', () => {
state.selectedIndex = idx;
tbody.querySelectorAll('tr').forEach((r, i) => r.classList.toggle('selected', i === idx));
});
tr.addEventListener('dblclick', () => {
if (state.editIndex === -1) {
state.selectedIndex = idx;
state.editIndex = idx;
state.backup = Object.assign({}, row);
renderGrid();
}
});
tbody.appendChild(tr);
});
}
function validateRowInputs(tr) {
const fn = tr.querySelector('input[name="firstname"]').value.trim();
const ln = tr.querySelector('input[name="lastname"]').value.trim();
const em = tr.querySelector('input[name="email"]').value.trim();
if (!fn || !ln) return false;
if (em && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(em)) return false;
return true;
}
function $(sel) {
return {
edatagrid(arg) {
if (typeof arg === 'object') {
state.opts = arg;
window.__initDone = fetch(arg.url).then(r => r.json()).then(rows => {
state.rows = rows;
renderGrid();
});
return this;
}
if (arg === 'addRow') {
if (state.editIndex !== -1) return this;
state.rows.push({ isNewRecord: true, firstname: '', lastname: '', phone: '', email: '' });
state.editIndex = state.rows.length - 1;
state.selectedIndex = state.editIndex;
renderGrid();
return this;
}
if (arg === 'cancelRow') {
if (state.editIndex === -1) return this;
const row = state.rows[state.editIndex];
if (row.isNewRecord) {
state.rows.splice(state.editIndex, 1);
} else if (state.backup) {
state.rows[state.editIndex] = state.backup;
}
state.editIndex = -1;
state.backup = null;
renderGrid();
return this;
}
if (arg === 'saveRow') {
if (state.editIndex === -1) return this;
const idx = state.editIndex;
const tr = document.querySelector('#dg tbody tr[data-idx="' + idx + '"]');
if (!validateRowInputs(tr)) {
window.__lastSaveValid = false;
return this;
}
window.__lastSaveValid = true;
const row = state.rows[idx];
const payload = {
firstname: tr.querySelector('input[name="firstname"]').value.trim(),
lastname: tr.querySelector('input[name="lastname"]').value.trim(),
phone: tr.querySelector('input[name="phone"]').value.trim(),
email: tr.querySelector('input[name="email"]').value.trim()
};
let targetUrl = state.opts.saveUrl;
if (!row.isNewRecord) {
targetUrl = state.opts.updateUrl;
payload.id = row.id;
}
window.__lastOp = fetch(targetUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams(payload).toString()
}).then(r => r.json()).then(saved => {
state.rows[idx] = saved;
state.editIndex = -1;
state.backup = null;
renderGrid();
});
return this;
}
if (arg === 'destroyRow') {
if (state.selectedIndex < 0) return this;
const idx = state.selectedIndex;
const row = state.rows[idx];
window.__lastOp = fetch(state.opts.destroyUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ id: row.id }).toString()
}).then(r => r.json()).then(res => {
if (res.success) {
state.rows.splice(idx, 1);
state.selectedIndex = -1;
renderGrid();
}
});
return this;
}
return this;
}
};
}
window.$ = $;
$('#dg').edatagrid({
url: '/get_users.php',
saveUrl: '/save_user.php',
updateUrl: '/update_user.php',
destroyUrl: '/destroy_user.php'
});
</script>
</body>
</html>
"""
def make_handler(conn):
class EDataGridHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
pass
def _send_json(self, obj):
body = json.dumps(obj).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path == "/":
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)
return
if self.path == "/get_users.php":
with DB_LOCK:
rows = [dict(r) for r in conn.execute("SELECT id, firstname, lastname, phone, email FROM users ORDER BY id")]
self._send_json(rows)
return
self.send_response(404)
self.end_headers()
def do_POST(self):
length = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(length).decode("utf-8")
form = {k: v[0] for k, v in urllib.parse.parse_qs(raw, keep_blank_values=True).items()}
if self.path == "/save_user.php":
with DB_LOCK:
cur = conn.execute(
"INSERT INTO users(firstname, lastname, phone, email) VALUES (?, ?, ?, ?)",
(form["firstname"], form["lastname"], form["phone"], form["email"]),
)
conn.commit()
uid = cur.lastrowid
self._send_json({"id": uid, **form})
return
if self.path == "/update_user.php":
uid = int(form["id"])
with DB_LOCK:
conn.execute(
"UPDATE users SET firstname=?, lastname=?, phone=?, email=? WHERE id=?",
(form["firstname"], form["lastname"], form["phone"], form["email"], uid),
)
conn.commit()
self._send_json({"id": uid, **form})
return
if self.path == "/destroy_user.php":
uid = int(form["id"])
with DB_LOCK:
conn.execute("DELETE FROM users WHERE id=?", (uid,))
conn.commit()
self._send_json({"success": True})
return
self.send_response(404)
self.end_headers()
return EDataGridHandler
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
conn = make_db()
server = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(conn))
port = server.server_address[1]
t = threading.Thread(target=server.serve_forever, daemon=True)
t.start()
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.goto(f"http://127.0.0.1:{port}/")
page.evaluate("() => window.__initDone")
# Case 1: Init + addRow inline editor + validation + saveRow
page.click("#btn-new")
has_editor = page.locator("#dg tbody tr.editing input").count()
page.fill('#dg tbody tr.editing input[name="firstname"]', "Lin")
page.click("#btn-save") # missing required lastname
blocked = not page.evaluate("() => window.__lastSaveValid")
page.fill('#dg tbody tr.editing input[name="lastname"]', "Zhou")
page.fill('#dg tbody tr.editing input[name="phone"]', "139-0003")
page.fill('#dg tbody tr.editing input[name="email"]', "lin@example.com")
page.click("#btn-save")
page.evaluate("() => window.__lastOp")
act1 = {
"inlineInputCount": has_editor,
"missingRequiredBlocked": blocked,
"rowCount": page.locator("#dg tbody tr").count(),
"savedRow": page.evaluate(
"() => Array.from(document.querySelectorAll('#dg tbody tr')[2].children).slice(1).map(td => td.textContent)"
),
}
exp1 = {
"inlineInputCount": 4,
"missingRequiredBlocked": True,
"rowCount": 3,
"savedRow": ["Lin", "Zhou", "139-0003", "lin@example.com"],
}
cases.append({
"name": "edatagrid_init_and_add_save",
"expected": exp1,
"actual": act1,
"passed": act1 == exp1,
})
# Case 2: Double-click inline edit -> cancelRow reverts -> edit again -> saveRow persists
page.dblclick('#dg tbody tr[data-idx="0"]')
page.fill('#dg tbody tr.editing input[name="phone"]', "999-9999")
page.click("#btn-cancel")
after_cancel = page.locator("#dg tbody tr").nth(0).locator("td").nth(3).inner_text()
page.dblclick('#dg tbody tr[data-idx="0"]')
page.fill('#dg tbody tr.editing input[name="phone"]', "139-8888")
page.fill('#dg tbody tr.editing input[name="email"]', "tom88@example.com")
page.click("#btn-save")
page.evaluate("() => window.__lastOp")
act2 = {
"phoneAfterCancel": after_cancel,
"phoneAfterSave": page.locator("#dg tbody tr").nth(0).locator("td").nth(3).inner_text(),
"emailAfterSave": page.locator("#dg tbody tr").nth(0).locator("td").nth(4).inner_text(),
}
exp2 = {
"phoneAfterCancel": "139-0001",
"phoneAfterSave": "139-8888",
"emailAfterSave": "tom88@example.com",
}
cases.append({
"name": "edatagrid_inline_update_and_cancel",
"expected": exp2,
"actual": act2,
"passed": act2 == exp2,
})
# Case 3: destroyRow removes selected row in DOM and SQLite
page.click('#dg tbody tr[data-idx="1"]')
page.click("#btn-destroy")
page.evaluate("() => window.__lastOp")
dom_names = page.evaluate(
"() => Array.from(document.querySelectorAll('#dg tbody tr')).map(tr => tr.children[1].textContent)"
)
with DB_LOCK:
db_count = conn.execute("SELECT COUNT(*) FROM users").fetchone()[0]
act3 = {"remainingNames": dom_names, "dbCount": db_count}
exp3 = {"remainingNames": ["Tom", "Lin"], "dbCount": 2}
cases.append({
"name": "edatagrid_destroy_row",
"expected": exp3,
"actual": act3,
"passed": act3 == exp3,
})
browser.close()
finally:
server.shutdown()
server.server_close()
conn.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/jeasyui-app-crud2-lab/explore-app-crud2.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-app-crud2.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a961.zip
课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip