PYTHON WEB 开发(人工智能) · 第 6 章实验指导书

Flask 用户注册与登录

通过逐步开发完成一个可运行的账户系统,理解表单校验、SQLite 参数化查询、密码哈希、Flask session 与 CSRF 防护。每一步都列出文件结构和需要的完整代码。

5 个开发步骤Flask + SQLite密码哈希与 session注册 · 登录 · 登出

实验目标与总体流程

完成实验后,你能独立运行注册、登录和退出流程,能解释用户数据保存在什么位置、密码如何保存,以及未登录用户为什么无法访问个人主页。

填写注册表单 → CSRF 校验 → 服务端验证字段 → 哈希密码 → SQLite 建立账户 → 登录时校验哈希 → 建立 session → 访问受保护页面 → POST 登出

安全边界:本项目是教学演示。数据库存储密码哈希,不存明文;API Key/SECRET_KEY 不写进源码。真实部署还需要 HTTPS、登录限速、密码重置和账户安全运营。

实验任务单:Flask 用户注册与登录(100 分)

按 5 个步骤完成实验并提交截图。每步包含排序、分值、功能要求、截图要求和判分规则;项目完整代码见本页后续开发步骤。

步骤 1:搭建项目骨架并准备安全配置

排序:1分值:15

步骤内容

功能要求

  1. 确认项目目录包含 app.py、templates/、static/、requirements.txt 和 .env.example。
  2. 创建虚拟环境并执行 pip install -r requirements.txt。
  3. 复制 .env.example 为本地 .env,为 SECRET_KEY 设置随机长字符串;不要把密钥写进源码或截图。
  4. 说明 COOKIE_SECURE=0 用于本机 HTTP 演示,HTTPS 部署时应设为 1。

截图要求

  • 图 1:项目目录结构和依赖安装成功(1 张)。
  • 图 2:环境变量配置,隐藏 SECRET_KEY 的值(1 张)。

判分规则

  • 目录和必要文件齐全——4 分
  • 虚拟环境中依赖安装成功——6 分
  • 密钥通过本地环境变量配置,没有写进源码或截图——5 分

对应完整文件:requirements.txt、.env.example、.gitignore。

步骤 2:初始化 SQLite 用户表

排序:2分值:20

步骤内容

功能要求

  1. 将数据库路径设为 instance/users.sqlite3,启动时自动创建 instance/ 目录。
  2. 编写 SQLite 连接上下文管理器,设置 row_factory,并在结束时提交或回滚、关闭连接。
  3. 使用 CREATE TABLE IF NOT EXISTS 创建 users 表,包含自增 ID、唯一用户名、密码哈希和注册时间。
  4. 运行 python app.py,确认数据库文件自动生成;使用 SQLite 工具查看表结构。

截图要求

  • 图 1:连接管理和建表代码(1 张)。
  • 图 2:SQLite 中的 users 表结构及数据库文件(1 张)。

判分规则

  • 数据库路径正确,目录可自动创建——5 分
  • 连接能提交/回滚并关闭,查询结果可按列名访问——8 分
  • 字段、主键和用户名唯一约束正确,重复启动不会覆盖数据——7 分

对应完整代码:database_connection()、initialize_database() 及启动时的初始化调用。

步骤 3:完成注册校验并安全保存密码

排序:3分值:25

步骤内容

功能要求

  1. 实现 GET/POST /register,表单包含用户名、密码和确认密码。
  2. 用户名限制为 3–20 位英文字母、数字或下划线,存入数据库前统一转为小写。
  3. 密码限制为 8–128 位,并检查两次输入一致;注册成功后跳转登录页。
  4. 使用 Werkzeug 的 generate_password_hash(..., method="scrypt") 保存哈希,并用 SQL 参数占位符写入数据库。
  5. 分别尝试有效注册、无效用户名、两次密码不一致和重复用户名。

截图要求

  • 图 1:注册表单和输入规则(1 张)。
  • 图 2:注册成功及重复用户名提示(1 张,可并排展示)。
  • 图 3:数据库中的 password_hash 字段,证明没有保存明文密码(1 张)。

判分规则

  • 用户名、密码长度及确认密码校验正确——8 分
  • 密码使用 scrypt 哈希,SQL 使用参数占位符——10 分
  • 重复用户名得到友好提示,注册成功后流程正确——7 分

对应完整文件:app.py 注册路由、templates/register.html 和 templates/base.html。

步骤 4:实现登录、session 和受保护页面

排序:4分值:25

步骤内容

功能要求

  1. 实现 GET/POST /login,使用参数化查询查找用户,并通过 check_password_hash 校验密码。
  2. 用户名不存在和密码错误时显示相同提示,避免泄露账户是否注册。
  3. 登录成功后清除旧 session,仅保存 user_id,然后进入个人主页。
  4. 使用 login_required 保护 /dashboard;个人主页按 session 中的用户 ID 查询账户资料。
  5. 测试正确密码、错误密码和未登录直接访问个人主页三种情况。

截图要求

  • 图 1:登录成功后的个人主页,能看到当前用户名(1 张)。
  • 图 2:错误密码提示和未登录访问个人主页后的跳转(1 张)。
  • 图 3:登录校验及 login_required 代码(1 张)。

判分规则

  • 参数化查询和密码哈希校验正确——8 分
  • 成功登录后 session 只保存用户 ID,错误提示统一——10 分
  • 未登录用户不能访问个人主页,登录后显示正确账户——7 分

对应完整文件:app.py 登录路由和装饰器、templates/login.html、templates/dashboard.html。

步骤 5:加入 CSRF 校验、登出并完成验收

排序:5分值:15

步骤内容

功能要求

  1. 为 POST 表单生成 session CSRF token,并在请求进入路由前使用 hmac.compare_digest 校验。
  2. 登出使用 POST 请求,通过 CSRF 校验后清空 session 并返回登录页。
  3. 确认 Cookie 设置了 HttpOnly 和 SameSite=Lax;本机 HTTP 与 HTTPS 环境分别配置 COOKIE_SECURE。
  4. 移除表单中的 token 后提交,确认服务端拒绝请求并显示 400 错误页;刷新后完成正常登录和登出。
  5. 整理最终截图,不展示真实密码、SECRET_KEY 或完整 Cookie。

截图要求

  • 图 1:表单 CSRF 隐藏字段和服务端校验代码(1 张)。
  • 图 2:正常登出结果和缺少 token 时的拒绝提示(1 张)。

判分规则

  • POST 表单带 token,服务端校验失败时拒绝请求——6 分
  • 登出通过 POST 清除登录状态,访问个人主页需要重新登录——5 分
  • Cookie 配置与截图处理符合要求,验收记录完整——4 分

对应完整文件:app.py CSRF 和登出逻辑,以及相关 Jinja 模板。

总分:100 分。每一步判分项合计等于该步骤分值;截图需清晰证明功能实际运行。

最终项目文件结构

flask-auth-demo/
├── app.py                         # 路由、验证、数据库、session、CSRF
├── .env.example                   # 本地环境变量模板
├── .gitignore
├── requirements.txt
├── README.md
├── instance/                      # 首次启动自动创建
│   └── users.sqlite3              # 用户账户数据库
├── templates/
│   ├── base.html                  # 共享导航与反馈消息
│   ├── login.html                 # 登录表单
│   ├── register.html              # 注册表单
│   ├── dashboard.html             # 登录后个人主页
│   └── error.html                 # 请求错误页面
└── static/
    └── style.css                  # 页面样式

项目文件可直接打开查看:

步骤导航

01准备

建立目录并准备环境

创建独立 Flask 项目目录,准备依赖、环境变量模板和 Git 忽略规则。数据库、真实密钥与 Python 虚拟环境都留在本机。

本步文件结构

flask-auth-demo/
├── app.py
├── .env.example
├── .gitignore
├── requirements.txt
├── README.md
├── templates/
└── static/

操作要点

在项目目录创建虚拟环境,安装 requirements.txt。复制 .env.example 为 .env,并将 SECRET_KEY 替换为随机长字符串。

完整代码

展开代码文件可查看完整内容;也可以点击文件名链接打开或下载对应源文件。

requirements.txt查看/下载源文件 ↗
# Flask provides routing, templates, flash messages, and signed sessions.
Flask>=3.0,<4.0
# Loads local settings from .env during development.
python-dotenv>=1.0,<2.0
.env.example查看/下载源文件 ↗
# Copy to .env and replace this placeholder with a long random secret.
# Do not commit the real .env file.
SECRET_KEY=replace-this-with-a-random-secret-before-use
# Use 1 only when serving the site over HTTPS.
COOKIE_SECURE=0
PORT=5007
.gitignore查看/下载源文件 ↗
# Keep local credentials, the SQLite database, and Python cache out of Git.
.env
.venv/
instance/
__pycache__/
*.py[cod]
02Flask 后端

实现数据库、注册登录和会话保护

后端完成 SQLite 建表、注册字段校验、密码哈希、登录验证、session 管理、CSRF 校验、受保护页面与登出。所有表单写操作由服务端重新校验。

本步文件结构

flask-auth-demo/
└── app.py  # 所有路由、安全辅助函数和 SQLite 访问逻辑

操作要点

按 database_connection → initialize_database → CSRF 校验 → register/login → login_required/dashboard/logout 阅读执行顺序。注册时只保存密码哈希;登录成功后 session 只记录 user_id。

完整代码

展开代码文件可查看完整内容;也可以点击文件名链接打开或下载对应源文件。

app.py查看/下载源文件 ↗
"""Flask 注册与登录教学示例:SQLite、密码哈希、会话和 CSRF 校验。"""

from __future__ import annotations

import hmac
import os
import re
import secrets
import sqlite3
from contextlib import contextmanager
from functools import wraps
from pathlib import Path

from dotenv import load_dotenv
from flask import Flask, abort, flash, redirect, render_template, request, session, url_for
from werkzeug.security import check_password_hash, generate_password_hash

load_dotenv()

app = Flask(__name__, instance_relative_config=True)
# SECRET_KEY 用于签名 Flask session;正式部署时必须通过环境变量设置固定密钥。
app.config.update(
    SECRET_KEY=os.getenv("SECRET_KEY") or secrets.token_hex(32),
    SESSION_COOKIE_HTTPONLY=True,
    SESSION_COOKIE_SAMESITE="Lax",
    SESSION_COOKIE_SECURE=os.getenv("COOKIE_SECURE", "0") == "1",
)

DATABASE = Path(app.instance_path) / "users.sqlite3"
USERNAME_PATTERN = re.compile(r"^[a-zA-Z0-9_]{3,20}$")
MIN_PASSWORD_LENGTH = 8
MAX_PASSWORD_LENGTH = 128


@contextmanager
def database_connection():
    """打开 SQLite 连接,并在退出时提交或回滚后关闭。"""
    connection = sqlite3.connect(DATABASE)
    connection.row_factory = sqlite3.Row
    try:
        yield connection
        connection.commit()
    except Exception:
        connection.rollback()
        raise
    finally:
        connection.close()


def initialize_database() -> None:
    """创建数据库目录和用户表;重复启动时不会覆盖已有账户。"""
    DATABASE.parent.mkdir(parents=True, exist_ok=True)
    with database_connection() as connection:
        connection.execute(
            """
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                username TEXT NOT NULL UNIQUE,
                password_hash TEXT NOT NULL,
                created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
            )
            """
        )


def get_csrf_token() -> str:
    """为当前浏览器会话生成可复用的表单校验令牌。"""
    token = session.get("csrf_token")
    if token is None:
        token = secrets.token_urlsafe(32)
        session["csrf_token"] = token
    return token


@app.context_processor
def inject_template_helpers() -> dict:
    """让所有模板都能通过 csrf_token() 生成隐藏表单字段。"""
    return {"csrf_token": get_csrf_token}


@app.before_request
def validate_csrf_token() -> None:
    """所有 POST 表单都必须带上当前 session 对应的 CSRF token。"""
    if request.method != "POST":
        return
    expected = session.get("csrf_token", "")
    submitted = request.form.get("csrf_token", "")
    if not expected or not submitted or not hmac.compare_digest(expected, submitted):
        abort(400, description="表单已过期或校验失败,请刷新页面后重试。")


def login_required(view):
    """未登录时先保存目标地址,再引导用户登录。"""
    @wraps(view)
    def wrapped_view(*args, **kwargs):
        if "user_id" not in session:
            flash("请先登录后再访问该页面。", "info")
            return redirect(url_for("login", next=request.path))
        return view(*args, **kwargs)

    return wrapped_view


@app.get("/")
def index():
    """根据登录状态进入个人页或登录页。"""
    if "user_id" in session:
        return redirect(url_for("dashboard"))
    return redirect(url_for("login"))


@app.route("/register", methods=["GET", "POST"])
def register():
    """校验注册表单,哈希密码后写入 SQLite。"""
    if "user_id" in session:
        return redirect(url_for("dashboard"))

    if request.method == "POST":
        # 用户名忽略大小写,数据库中的唯一值统一存为小写。
        username = request.form.get("username", "").strip().lower()
        password = request.form.get("password", "")
        confirmation = request.form.get("password_confirmation", "")

        if not USERNAME_PATTERN.fullmatch(username):
            flash("用户名须为 3–20 位字母、数字或下划线。", "error")
        elif not MIN_PASSWORD_LENGTH <= len(password) <= MAX_PASSWORD_LENGTH:
            flash(f"密码长度须为 {MIN_PASSWORD_LENGTH}–{MAX_PASSWORD_LENGTH} 个字符。", "error")
        elif password != confirmation:
            flash("两次输入的密码不一致。", "error")
        else:
            # 数据库只保存哈希值;绝不保存明文密码。
            password_hash = generate_password_hash(password, method="scrypt")
            try:
                with database_connection() as connection:
                    connection.execute(
                        "INSERT INTO users (username, password_hash) VALUES (?, ?)",
                        (username, password_hash),
                    )
            except sqlite3.IntegrityError:
                flash("这个用户名已被注册,请换一个用户名。", "error")
            else:
                flash("注册成功,请使用新账户登录。", "success")
                return redirect(url_for("login"))

    return render_template("register.html")


@app.route("/login", methods=["GET", "POST"])
def login():
    """验证用户名和密码,成功后创建干净的新登录 session。"""
    if "user_id" in session:
        return redirect(url_for("dashboard"))

    if request.method == "POST":
        username = request.form.get("username", "").strip().lower()
        password = request.form.get("password", "")
        with database_connection() as connection:
            user = connection.execute(
                "SELECT id, username, password_hash FROM users WHERE username = ?",
                (username,),
            ).fetchone()

        # 统一提示,避免通过错误文案判断某个用户名是否已经注册。
        if user is None or not check_password_hash(user["password_hash"], password):
            flash("用户名或密码不正确。", "error")
        else:
            # 清除旧 session 内容后只写入用户 ID,降低会话固定风险。
            session.clear()
            session["user_id"] = int(user["id"])
            destination = request.args.get("next", "")
            # 只接受站内相对路径,避免 next 参数造成外站跳转。
            if (
                not destination.startswith("/")
                or destination.startswith("//")
                or "\\" in destination
            ):
                destination = url_for("dashboard")
            return redirect(destination)

    return render_template("login.html")


@app.get("/dashboard")
@login_required
def dashboard():
    """登录后查询当前账户资料并显示欢迎页面。"""
    with database_connection() as connection:
        user = connection.execute(
            "SELECT id, username, created_at FROM users WHERE id = ?",
            (session["user_id"],),
        ).fetchone()
    if user is None:
        session.clear()
        flash("账户状态已失效,请重新登录。", "info")
        return redirect(url_for("login"))
    return render_template("dashboard.html", user=user)


@app.post("/logout")
@login_required
def logout():
    """清除登录状态;登出使用 POST 并受 CSRF 保护。"""
    session.clear()
    flash("你已安全退出。", "success")
    return redirect(url_for("login"))


@app.errorhandler(400)
def bad_request(error):
    """将 CSRF 校验失败等 400 错误显示为友好页面。"""
    message = getattr(error, "description", "请求无效,请返回上一页重试。")
    return render_template("error.html", message=message), 400


initialize_database()

if __name__ == "__main__":
    # 仅供本机课堂演示;对外部署请使用生产 WSGI 服务器和 HTTPS。
    app.run(host="127.0.0.1", port=int(os.getenv("PORT", "5007")), debug=os.getenv("FLASK_DEBUG") == "1")
03Jinja 模板

制作共享布局与注册登录表单

base.html 统一提供导航和消息提示;login.html、register.html 分别提供登录与注册表单。每个 POST 表单带 CSRF 隐藏字段。

本步文件结构

flask-auth-demo/
└── templates/
    ├── base.html
    ├── login.html
    └── register.html

操作要点

检查表单 action 对应 app.py 的路由名;autocomplete 帮助浏览器管理密码,前端 HTML 属性改善输入体验,但服务器端规则才是真正的校验。

完整代码

展开代码文件可查看完整内容;也可以点击文件名链接打开或下载对应源文件。

templates/base.html查看/下载源文件 ↗
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="theme-color" content="#f4f6fb">
  <title>{% block title %}Flask 账户中心{% endblock %}</title>
  <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
  <div class="page-shell">
    <header class="topbar">
      <a class="brand" href="{{ url_for('index') }}"><span class="brand-mark">F</span><span>Flask 账户中心</span></a>
      <nav aria-label="账户导航">
        {% if session.get('user_id') %}
          <a href="{{ url_for('dashboard') }}">个人主页</a>
          <form class="nav-form" method="post" action="{{ url_for('logout') }}">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            <button class="nav-logout" type="submit">退出登录</button>
          </form>
        {% else %}
          <a href="{{ url_for('login') }}">登录</a>
          <a href="{{ url_for('register') }}">注册</a>
        {% endif %}
      </nav>
    </header>

    <main>
      <!-- Flash messages display validation results and account status safely. -->
      {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
          <div class="flash-list" role="status" aria-live="polite">
            {% for category, message in messages %}
              <p class="flash flash-{{ category }}">{{ message }}</p>
            {% endfor %}
          </div>
        {% endif %}
      {% endwith %}

      {% block content %}{% endblock %}
    </main>

    <footer>Flask 注册登录教学项目 · SQLite 本地数据</footer>
  </div>
</body>
</html>
templates/login.html查看/下载源文件 ↗
{% extends "base.html" %}
{% block title %}登录 · Flask 账户中心{% endblock %}
{% block content %}
<section class="auth-layout">
  <div class="intro-panel">
    <p class="eyebrow">WELCOME BACK</p>
    <h1>登录你的账户</h1>
    <p>使用用户名和密码登录,进入受保护的个人主页。</p>
    <ul class="feature-list"><li>密码以哈希形式保存在 SQLite</li><li>登录状态由安全签名的 session 维护</li><li>表单提交带有 CSRF 校验</li></ul>
  </div>
  <div class="form-panel">
    <div class="form-heading"><span class="form-icon">↗</span><div><h2>欢迎回来</h2><p>请输入账户信息继续</p></div></div>
    <form method="post" action="{{ url_for('login', next=request.args.get('next', '')) }}">
      <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
      <label for="username">用户名</label>
      <input id="username" name="username" type="text" minlength="3" maxlength="20" pattern="[A-Za-z0-9_]{3,20}" autocomplete="username" placeholder="输入用户名" required autofocus>
      <label for="password">密码</label>
      <input id="password" name="password" type="password" maxlength="128" autocomplete="current-password" placeholder="输入密码" required>
      <button class="primary-button" type="submit">登录 <span aria-hidden="true">→</span></button>
    </form>
    <p class="switch-prompt">还没有账户? <a href="{{ url_for('register') }}">立即注册</a></p>
  </div>
</section>
{% endblock %}
templates/register.html查看/下载源文件 ↗
{% extends "base.html" %}
{% block title %}注册 · Flask 账户中心{% endblock %}
{% block content %}
<section class="auth-layout">
  <div class="intro-panel register-intro">
    <p class="eyebrow">CREATE ACCOUNT</p>
    <h1>创建新账户</h1>
    <p>完成注册后即可登录并访问个人主页。</p>
    <ul class="feature-list"><li>用户名 3–20 位,只能使用字母、数字和下划线</li><li>密码长度 8–128 位,数据库仅保存哈希</li><li>用户名不区分大小写</li></ul>
  </div>
  <div class="form-panel">
    <div class="form-heading"><span class="form-icon">+</span><div><h2>新用户注册</h2><p>填写信息创建账户</p></div></div>
    <form method="post" action="{{ url_for('register') }}">
      <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
      <label for="username">用户名</label>
      <input id="username" name="username" type="text" minlength="3" maxlength="20" pattern="[A-Za-z0-9_]{3,20}" autocomplete="username" placeholder="例如:student_01" required autofocus>
      <label for="password">设置密码</label>
      <input id="password" name="password" type="password" minlength="8" maxlength="128" autocomplete="new-password" placeholder="至少 8 个字符" required>
      <label for="password_confirmation">确认密码</label>
      <input id="password_confirmation" name="password_confirmation" type="password" minlength="8" maxlength="128" autocomplete="new-password" placeholder="再次输入密码" required>
      <button class="primary-button" type="submit">创建账户 <span aria-hidden="true">→</span></button>
    </form>
    <p class="switch-prompt">已有账户? <a href="{{ url_for('login') }}">返回登录</a></p>
  </div>
</section>
{% endblock %}
04页面与样式

完成受保护页面、错误页与样式

dashboard.html 展示当前登录账户信息;error.html 展示 CSRF 校验失败等错误。style.css 负责账户页、消息条和手机布局。

本步文件结构

flask-auth-demo/
├── templates/
│   ├── dashboard.html
│   └── error.html
└── static/
    └── style.css

操作要点

尝试直接访问 /dashboard:未登录时应转到登录页。登录后页面显示从数据库查询的账户资料,退出按钮通过 POST 提交。

完整代码

展开代码文件可查看完整内容;也可以点击文件名链接打开或下载对应源文件。

templates/dashboard.html查看/下载源文件 ↗
{% extends "base.html" %}
{% block title %}个人主页 · Flask 账户中心{% endblock %}
{% block content %}
<section class="dashboard-card">
  <p class="eyebrow">ACCOUNT OVERVIEW</p>
  <h1>你好,{{ user["username"] }}</h1>
  <p class="dashboard-lead">你已成功登录。这个页面由登录保护,未登录用户会被引导到登录页。</p>
  <div class="account-details">
    <div><span>用户 ID</span><strong>{{ user["id"] }}</strong></div>
    <div><span>用户名</span><strong>{{ user["username"] }}</strong></div>
    <div><span>注册时间(UTC)</span><strong>{{ user["created_at"] }}</strong></div>
  </div>
  <form method="post" action="{{ url_for('logout') }}">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <button class="secondary-button" type="submit">退出登录</button>
  </form>
</section>
{% endblock %}
templates/error.html查看/下载源文件 ↗
{% extends "base.html" %}
{% block title %}请求未通过 · Flask 账户中心{% endblock %}
{% block content %}
<section class="error-card">
  <p class="eyebrow">REQUEST CHECK</p>
  <h1>请求未通过校验</h1>
  <p>{{ message }}</p>
  <a class="primary-link" href="{{ url_for('index') }}">返回账户中心</a>
</section>
{% endblock %}
static/style.css查看/下载源文件 ↗
/* Theme tokens keep colors and spacing consistent across account pages. */
:root {
  font-family: "Segoe UI", "Microsoft YaHei", system-ui, sans-serif;
  color: #1d2939;
  background: #f3f5fa;
  font-synthesis: none;
  text-rendering: optimizeLegibility;
  --ink: #1d2939;
  --muted: #7c8798;
  --line: #e6eaf1;
  --blue: #3f67d7;
  --surface: #ffffff;
}

* { box-sizing: border-box; }

body {
  min-width: 320px;
  min-height: 100vh;
  margin: 0;
  background: radial-gradient(ellipse at 15% 0, #e8edff 0, transparent 32%), #f3f5fa;
}

/* Center the site and keep the footer aligned below short pages. */
.page-shell {
  width: min(1080px, calc(100% - 36px));
  min-height: 100vh;
  margin: auto;
  display: flex;
  flex-direction: column;
}

.topbar {
  display: flex;
  min-height: 76px;
  align-items: center;
  justify-content: space-between;
  gap: 18px;
  border-bottom: 1px solid #e1e6ef;
}

.brand, .topbar nav, .nav-form { display: flex; align-items: center; }
.brand { gap: 10px; color: var(--ink); font-weight: 700; text-decoration: none; }
.brand-mark { display: grid; width: 32px; height: 32px; place-items: center; border-radius: 10px; background: #e7edff; color: var(--blue); }
.topbar nav { gap: 18px; }
.topbar nav a, .nav-logout { color: #5c687b; font: inherit; font-size: 13px; text-decoration: none; }
.topbar nav a:hover, .nav-logout:hover { color: var(--blue); }
.nav-form { margin: 0; }
.nav-logout { padding: 0; border: 0; background: transparent; cursor: pointer; }

main { flex: 1; padding: 36px 0; }

/* Flash messages give a shared place for form errors and success feedback. */
.flash-list { display: grid; gap: 8px; margin-bottom: 16px; }
.flash { margin: 0; padding: 11px 14px; border-radius: 9px; font-size: 13px; }
.flash-error { border: 1px solid #f2caca; background: #fff1f1; color: #a63d3d; }
.flash-success { border: 1px solid #c8e9d7; background: #effaf3; color: #28764b; }
.flash-info { border: 1px solid #d5def5; background: #f0f4ff; color: #3655a4; }

/* Registration and login use a two-column intro and form layout. */
.auth-layout {
  display: grid;
  grid-template-columns: 1fr 440px;
  min-height: 510px;
  overflow: hidden;
  border: 1px solid var(--line);
  border-radius: 20px;
  background: var(--surface);
  box-shadow: 0 18px 45px #1d2d4a0d;
}

.intro-panel {
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: clamp(28px, 6vw, 66px);
  color: #fff;
  background: linear-gradient(140deg, #203b91, #5578e1);
}
.intro-panel .eyebrow, .dashboard-card .eyebrow, .error-card .eyebrow { color: #dbe5ff; }
.eyebrow { margin: 0 0 11px; color: #8995aa; font-size: 11px; font-weight: 700; letter-spacing: .13em; }
.intro-panel h1, .dashboard-card h1, .error-card h1 { margin: 0; font-size: clamp(28px, 4vw, 38px); letter-spacing: -.04em; line-height: 1.2; }
.intro-panel > p:not(.eyebrow) { max-width: 390px; margin: 15px 0 20px; color: #edf2ff; font-size: 14px; line-height: 1.8; }
.feature-list { display: grid; gap: 11px; margin: 0; padding: 0; list-style: none; color: #e3eaff; font-size: 12px; }
.feature-list li::before { margin-right: 9px; color: #9fbcff; content: "✓"; }

.form-panel { align-self: center; padding: 36px clamp(22px, 4vw, 42px); }
.form-heading { display: flex; align-items: center; gap: 12px; margin-bottom: 22px; }
.form-icon { display: grid; width: 40px; height: 40px; place-items: center; border-radius: 12px; background: #edf2ff; color: var(--blue); font-size: 21px; }
.form-heading h2 { margin: 0; font-size: 20px; }
.form-heading p { margin: 4px 0 0; color: var(--muted); font-size: 12px; }

/* Native browser validation complements the server-side checks in app.py. */
.form-panel form:not(.nav-form) { display: grid; }
.form-panel label { margin: 13px 0 7px; color: #465267; font-size: 12px; font-weight: 600; }
.form-panel input:not([type="hidden"]) { width: 100%; min-height: 43px; padding: 0 12px; border: 1px solid #dce2eb; border-radius: 8px; outline: none; background: #fff; color: var(--ink); font: inherit; font-size: 13px; }
.form-panel input:focus { border-color: #7995ea; box-shadow: 0 0 0 3px #4778f51c; }
.form-panel input::placeholder { color: #a5adba; }
.primary-button, .secondary-button, .primary-link {
  display: inline-flex;
  min-height: 43px;
  align-items: center;
  justify-content: center;
  gap: 14px;
  margin-top: 22px;
  padding: 0 16px;
  border: 0;
  border-radius: 8px;
  background: var(--blue);
  color: #fff;
  font: inherit;
  font-size: 13px;
  font-weight: 700;
  text-decoration: none;
  cursor: pointer;
}
.primary-button:hover, .primary-link:hover { background: #3158c3; }
.switch-prompt { margin: 19px 0 0; color: var(--muted); font-size: 12px; text-align: center; }
.switch-prompt a { color: var(--blue); font-weight: 700; text-decoration: none; }

/* The dashboard displays only the account associated with the session ID. */
.dashboard-card, .error-card {
  max-width: 760px;
  margin: 35px auto;
  padding: clamp(25px, 5vw, 48px);
  border: 1px solid var(--line);
  border-radius: 18px;
  background: var(--surface);
  box-shadow: 0 15px 40px #1d2d4a0b;
}
.dashboard-card { background: linear-gradient(145deg, #263f8f, #4569cd); color: #fff; }
.dashboard-lead { margin: 14px 0 25px; color: #e4eaff; font-size: 14px; line-height: 1.8; }
.account-details { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
.account-details div { padding: 14px; border: 1px solid #ffffff30; border-radius: 10px; background: #ffffff12; }
.account-details span, .account-details strong { display: block; }
.account-details span { color: #cbd7ff; font-size: 10px; }
.account-details strong { margin-top: 7px; overflow-wrap: anywhere; font-size: 13px; }
.secondary-button { border: 1px solid #ffffff75; background: transparent; }
.secondary-button:hover { background: #ffffff18; }
.error-card p:not(.eyebrow) { color: #667085; }
.error-card .eyebrow { color: #8792a5; }
.error-card .primary-link { margin-top: 12px; }

footer { padding: 20px 0 24px; color: #9aa3b1; font-size: 11px; text-align: center; }

/* Stack the intro and form on phones and allow account details to wrap. */
@media (max-width: 760px) {
  .page-shell { width: min(100% - 22px, 600px); }
  .topbar { min-height: 64px; }
  .auth-layout { grid-template-columns: 1fr; }
  .intro-panel { min-height: 260px; padding: 30px; }
  .form-panel { width: 100%; max-width: 480px; justify-self: center; }
  .account-details { grid-template-columns: 1fr; }
  main { padding: 22px 0; }
}

@media (max-width: 420px) {
  .brand { font-size: 13px; }
  .topbar nav { gap: 10px; }
  .form-panel { padding: 27px 20px; }
}
05运行验收

启动应用并完成验收

SQLite 数据表会在 Flask 启动时自动创建。手动执行注册、重复用户名、错误密码、受保护页访问、登出及 CSRF 错误场景,观察提示和页面跳转。

本步文件结构

flask-auth-demo/
├── README.md  # 环境配置、规则和运行说明
└── instance/
    └── users.sqlite3  # 首次启动自动创建,不提交到 Git

操作要点

启动命令见下方。用浏览器访问 http://127.0.0.1:5007,完成验收清单。不要在截图或公开代码中暴露真实密码或 SECRET_KEY。

完整代码

展开代码文件可查看完整内容;也可以点击文件名链接打开或下载对应源文件。

README.md查看/下载源文件 ↗
# Flask 注册与登录教学项目

独立运行的 Flask 账户示例,演示注册、登录、登出和受保护页面。项目使用 SQLite 保存用户记录,以 Werkzeug 的 scrypt 哈希保存密码,并用 Flask session 维护登录状态。

## 功能与实现

- 注册校验用户名、密码长度、两次密码一致性和用户名唯一性。
- 密码使用 `generate_password_hash` 哈希,登录时用 `check_password_hash` 验证。
- 所有写操作通过带随机 token 的表单进行 CSRF 校验。
- SQL 使用参数占位符;登录失败使用统一提示,减少账户枚举信息。
- 登录后只在 session 中保存用户 ID;退出时清除整个 session。
- 数据库存放于 `instance/users.sqlite3`,不会放在公开静态目录。
- SQLite 在首次启动时自动创建表。请勿将真实账户数据用于课堂演示以外的用途。

## 安装和启动(PowerShell)

```powershell
cd static/course/python_web_ai/section-6/flask-auth-demo
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
Copy-Item .env.example .env
```

在 `.env` 中将 `SECRET_KEY` 替换为随机长字符串,然后启动:

```powershell
python app.py
```

浏览器访问 <http://127.0.0.1:5007>。程序首次启动时会创建 `instance/users.sqlite3`。

## 配置说明

| 变量 | 用途 | 默认值 |
| --- | --- | --- |
| `SECRET_KEY` | 签名 Flask session Cookie | 未提供时启动时随机生成,重启后会使旧 session 失效 |
| `COOKIE_SECURE` | 是否只通过 HTTPS 发送 Cookie | `0`,本机 HTTP 演示;部署 HTTPS 后设为 `1` |
| `PORT` | 本机开发端口 | `5007` |
| `FLASK_DEBUG` | Flask 调试模式 | 未设置时关闭 |

## 用户名与密码规则

- 用户名 3–20 位,仅允许英文字母、数字和下划线;存储时统一转为小写,因此大小写不区分。
- 密码 8–128 个字符;示例为了教学简化策略,没有强制字符种类或密码重用规则。
- 用户表仅有 `username`、`password_hash` 和注册时间等字段,不存储明文密码。

## 项目结构

```text
flask-auth-demo/
├── app.py
├── .env.example
├── .gitignore
├── requirements.txt
├── README.md
├── instance/                 # 首次启动自动创建,保存本地 SQLite 数据库
├── templates/
│   ├── base.html
│   ├── login.html
│   ├── register.html
│   ├── dashboard.html
│   └── error.html
└── static/
    └── style.css
```

这是课堂演示程序。真实服务还应考虑 HTTPS、登录限速、多因素认证、密码重置、账户锁定、审计与备份等运营要求。

安装、运行与验收

PowerShell 安装命令

cd D:\wwwroot\teacher_gao\static\course\python_web_ai\section-6\flask-auth-demo
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
Copy-Item .env.example .env

打开 .env,将 SECRET_KEY 换成长随机值,然后运行:

python app.py

浏览器访问 http://127.0.0.1:5007。首次启动时自动在 instance/users.sqlite3 创建数据库与用户表。

验收清单

  • 注册有效用户名和密码后,可以通过成功提示跳转到登录页。
  • 重复注册同一用户名会显示友好提示;大小写不同的同名账号也应视为重复。
  • 用户名长度/字符不符合规则、密码过短、确认密码不一致时无法注册。
  • 登录错误时提示统一,不区分“用户名不存在”或“密码错误”。
  • 未登录访问 /dashboard 会被引导到登录;登录后显示正确账户。
  • 登出后回到登录页,再访问个人主页仍需重新登录。
  • 移除表单中的 CSRF hidden token 后提交,服务端拒绝请求。

课堂讨论:为什么不能把密码原文写入 users 表?为什么登出按钮使用 POST?模板中的 pattern/required 能否替代后端校验?