You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask程序运行不稳定,页面重定向异常及内部服务器错误求助

Flask登录注册程序异常排查与修复方案

核心问题梳理

  1. 存在两个独立的Flask应用文件(create.py和app.py),运行时仅加载一个实例,导致路由缺失或冲突
  2. 视图函数端点名称不统一(sign_up vs signup),模板中url_for调用的端点与实际定义不匹配
  3. 数据库连接未正确关闭,存在资源泄漏风险
  4. 错误信息未传递到模板,用户无法获取操作反馈
  5. 注册成功后跳转的home端点未定义

修复步骤

1. 合并Flask应用文件

删除create.py,将其数据库初始化和注册功能合并到app.py,确保仅存在一个Flask实例:

from flask import Flask, render_template, request, redirect, url_for
import hashlib
import sqlite3

app = Flask(__name__)
app.config['DEBUG'] = True

def init_db():
    with sqlite3.connect("user_login_data.db") as connection:
        cursor = connection.cursor()
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS users (
                username TEXT PRIMARY KEY,
                password TEXT NOT NULL
            )
        """)
        connection.commit()

init_db()

@app.route('/', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        username = request.form.get("username")
        password = request.form.get("password")

        hashed_password = hashlib.sha1(password.encode()).hexdigest()

        # 使用with语句自动关闭数据库连接
        with sqlite3.connect('user_login_data.db') as connection:
            cursor = connection.cursor()
            query = "SELECT username, password FROM users WHERE username = ? AND password = ?"
            cursor.execute(query, (username, hashed_password))
            result = cursor.fetchall()

        if len(result) == 0:
            error = "Username or password is incorrect."
        else:
            return render_template("home_page.html")

    return render_template("index.html", error=error)

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    error = None
    if request.method == 'POST':
        username = request.form.get("username")
        password = request.form.get("password")
        confirm_password = request.form.get("confirm_password")

        if password != confirm_password:
            error = "Passwords do not match."
        else:
            hashed_password = hashlib.sha1(password.encode()).hexdigest()
            try:
                with sqlite3.connect("user_login_data.db") as connection:
                    cursor = connection.cursor()
                    cursor.execute(
                        "INSERT INTO users (username, password) VALUES (?, ?)",
                        (username, hashed_password)
                    )
                    connection.commit()
                    # 注册成功后跳转登录页
                    return redirect(url_for('login'))
            except sqlite3.IntegrityError:
                error = "Username already exists. Please try another."

    return render_template("signup.html", error=error)

# 新增主页视图(按需调整)
@app.route('/home')
def home():
    return render_template("home_page.html")

if __name__ == '__main__':
    app.run(debug=True)

2. 修复模板端点匹配与错误显示

修改index.html:

  • 统一url_for调用的端点名称
  • 添加错误信息显示区域
<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="/static/style.css">
    <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">

    <title>Login</title>
</head>
<body>
    <center>
    <div class = "main"> 
        <h1 class = "sign"> Sign in </h1>
        <!-- 错误信息提示 -->
        {% if error %}
            <p style="color: red;">{{ error }}</p>
        {% endif %}
        <form method="POST" class = "form1" >
            <br>
            <input class = "un" type="text" name="username"  align="center" placeholder="Username" required>
            <input class= "pass" type="password" name="password" align="center" placeholder="Password" minlength="8" required />
            <input class = "submit" type="submit"  value="Sign in" />
            <br><br>
            <p class="forgot" align="center"> Don't have an account? <a href="{{ url_for('signup') }}"> Sign up</a> </p>
        </form>
    </div>
    </center>
</body>
</html>

修改signup.html:

  • 添加错误信息显示区域
  • 修复无效的资源链接
<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="/static/styles.css">
    <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">

    <title>Sign Up</title>
</head>
<body>
<center>
    <div class="main">
        <h1 class = "sign" >Create an Account</h1>
        <!-- 错误信息提示 -->
        {% if error %}
            <p style="color: red;">{{ error }}</p>
        {% endif %}
        <form method="POST" class = "form">
            <br><br>
            <label for="username"></label>
            <input class = "un" type="text" name="username" placeholder="Enter your username here " required>
            <br>
            <label for="username"></label>
            <input class = "pass" type="password" name="password" placeholder="Enter your password here" required>
            <br>
            <label for="username"></label>
            <input class = "pass" type="password" name="confirm_password" placeholder="Re-enter password here" required>
            <br><br><br>
            <button class = "submit" type="submit">Create Account</button>
            <br><br><br>
            <p class="forgot" align="center"> have an account? <a href="{{ url_for('login') }}"> Sign in</a> </p>
        </form>
    </div>
</center>
</body>
</html>

3. 其他细节调整

  • 确保home_page.html存在,或根据需求修改跳转目标
  • 统一静态文件名称:style.css和styles.css保持一致
  • 运行前确认模板文件在templates目录,静态文件在static目录

运行验证

  1. 删除原create.py文件
  2. 执行python app.py启动应用(或设置FLASK_APP=app.py后运行flask run)

内容的提问来源于stack exchange,提问作者Anas Bousrih

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 02:02:01