文章

Python 首批细教程 · 03A:从 HTML 表单到 SQLite,一步做出本地留言板

#269 · 2026-05-13 · Python 教程拆解

对应原仓库Day21-30/21-30.Web前端概述.mdDay31-35/31-35.玩转Linux操作系统.mdDay36-40/36.关系型数据库和MySQL概述.md

已提供可运行示例/tutorial-assets/python-100-days/03a-html-http-sqlite/(站点源码路径:blog-src/static/tutorial-assets/python-100-days/03a-html-http-sqlite/

这一篇的核心目标不是学完整前端,也不是直接冲大型数据库,而是先做出一个有页面、有服务、有存储的最小系统。

Step 1:写页面

示例目录已经提供 index.html(站点源码路径:blog-src/static/tutorial-assets/python-100-days/03a-html-http-sqlite/index.html):

<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>留言板</title>
  <style>
    body { max-width: 720px; margin: 40px auto; font-family: sans-serif; }
    input, textarea { width: 100%; margin: 8px 0; padding: 8px; }
  </style>
</head>
<body>
  <h1>留言板</h1>
  <input id="author" placeholder="你的名字">
  <textarea id="content" rows="4" placeholder="留言内容"></textarea>
  <button>先做静态原型</button>
</body>
</html>

Step 2:起本地服务

cd blog-src/static/tutorial-assets/python-100-days/03a-html-http-sqlite
python -m http.server 9000

浏览器访问 http://127.0.0.1:9000

这个动作很小,但它让你开始理解:

  • 目录如何被服务出去;
  • 本地端口如何提供访问;
  • 页面不是“打开文件”这么简单,而是通过 HTTP 被交付。

Step 3:接 SQLite

示例目录已经提供 init_db.py(站点源码路径:blog-src/static/tutorial-assets/python-100-days/03a-html-http-sqlite/init_db.py):

import sqlite3

conn = sqlite3.connect("guestbook.db")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS messages (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    author TEXT NOT NULL,
    content TEXT NOT NULL
)
""")
cursor.execute(
    "INSERT INTO messages(author, content) VALUES (?, ?)",
    ("Copilot", "欢迎来到留言板")
)
conn.commit()
conn.close()
print("guestbook.db 初始化完成")

运行:

python init_db.py

Step 4:查询留言

示例目录已经提供 query_db.py(站点源码路径:blog-src/static/tutorial-assets/python-100-days/03a-html-http-sqlite/query_db.py):

import sqlite3

conn = sqlite3.connect("guestbook.db")
cursor = conn.cursor()
cursor.execute("SELECT id, author, content FROM messages ORDER BY id DESC")
rows = cursor.fetchall()
for row in rows:
    print(row)
conn.close()

这一步对应原仓库哪部分

  • HTML:对应 Day21-30 里“标签承载内容”。
  • HTTP 服务:对应 Day31-35 里“程序怎么运行、怎么被访问”。
  • 数据库存储:对应 Day36-40 里“数据要落到表里,而不是只活在内存里”。

进阶任务

  1. 再写一个 insert_message.py,从终端读作者和内容后写入数据库。
  2. index.html 增加“最近留言”列表区域。
  3. 如果本机有 sqlite3 命令,手工执行 .tablesselect * from messages;

常见坑

  • 只会写 HTML,不会起服务。
  • 只会起服务,不会让数据落库。
  • 页面、服务、数据完全分开看,结果做不成系统。