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

Flask项目登录注册页报错:werkzeug.routing.exceptions.BuildError

问题排查与解决

错误1:BuildError: Could not build url for endpoint 'Register'

错误提示已明确指出问题:login.html中使用{{url_for('Register')}}调用端点,但Flask的端点名称对应视图函数的小写名称(你的视图函数为def register()),大小写不匹配导致无法构建URL。

修复方法:
修改login.html中的注册链接:

<a href="{{url_for('register')}}">Register</a>

错误2:Internal Server Error(访问/login或/register时触发)

该错误由两个核心问题导致:

  1. 全局数据库连接被提前关闭:hello视图中直接关闭了全局的cursor和connection,后续请求(如/login、/register)尝试使用已关闭的连接时直接报错。
  2. 代码缩进错误:Python对缩进敏感,hello和login视图中存在多处缩进错位,引发运行时错误。

修复步骤:

步骤1:修复数据库连接管理

不要在hello视图中关闭全局连接,改为每次请求创建独立游标,请求结束后仅关闭游标:

@app.route('/hello',methods=["GET","POST"])
def hello():
    # 每次请求创建新游标
    cursor = connection.cursor()
    player_records = []
    if request.method == "GET" or request.method == "POST":
        postgre_str="select * from play.player_list"
        cursor.execute(postgre_str)
        player_records = cursor.fetchall()
    
    if request.method == "POST":
        player_name=request.form.get("playername")
        # 改用参数化查询避免SQL注入
        postgre_str="insert into play.player_list(player_name) values(%s)"
        cursor.execute(postgre_str, (player_name,))
        connection.commit()
    # 仅关闭当前请求的游标,保留全局连接
    cursor.close()
    return render_template('index.html',player_records=player_records)

步骤2:修正所有缩进错误

调整app.py中错位的缩进:

@app.route('/', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != 'admin' or request.form['password'] != 'admin':
            error = 'Invalid Credentials. Please try again.'
        else:
            return redirect(url_for('hello'))
    return render_template('login.html', error=error)

步骤3:修复register.html的表单提交地址

register.html中表单action="/register.html"指向错误,改为正确的端点路径:

<form method="POST" action="/register">

额外建议

  • SQL注入风险:避免使用字符串拼接生成SQL语句,始终采用参数化查询(上述修复已调整)。
  • 数据库连接优化:全局连接在多请求场景下不稳定,建议使用Flask-SQLAlchemy等扩展管理连接,或在请求生命周期内动态创建/关闭连接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 05:37:17