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

Flask登录模块Python文件无法运行问题求助及代码排查

Python登录功能运行错误修复方案

核心问题分析与修复步骤

  • 函数重复定义冲突:两个/login路由绑定了同名login函数,后定义的函数会覆盖前一个,引发路由逻辑混乱。需合并GET/POST请求处理逻辑到同一个函数。
  • 表单提交路由不匹配:HTML表单的action指向login_post,但Python代码中无此函数,需修正为对应处理登录的路由函数名。
  • SQL语法错误:SQL语句中% s存在多余空格,应为%s,否则会导致数据库查询失败。
  • 重定向方式错误:登录成功后直接用redirect('profile.html')不符合Flask规范,需通过url_for指向对应路由,消息传递需调整逻辑。

修正后的Python代码

# 合并GET/POST请求处理到同一个路由函数
@app.route('/login', methods=['GET', 'POST'])
def login():
    mesage = ''
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
        username = request.form['username']
        password = request.form['password']
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        # 修正SQL语句中的空格问题
        cursor.execute('SELECT * FROM user WHERE username = %s AND password = %s', (username, password,))
        user = cursor.fetchone()
        if user:
            session['loggedin'] = True
            session['email'] = user['email']
            # 重定向到profile路由(需确保存在对应的/profile路由函数)
            return redirect(url_for('profile'))
        else:
            mesage = 'Please enter correct username / password!'
    # GET请求或验证失败时渲染登录页面
    return render_template('login.html', mesage=mesage)

# 补充profile路由示例(若不存在)
@app.route('/profile')
def profile():
    # 验证用户是否已登录
    if 'loggedin' in session:
        return render_template('profile.html', email=session['email'], mesage='Logged in successfully!')
    # 未登录则重定向到登录页
    return redirect(url_for('login'))

修正后的HTML代码

<img src="../static/assets/Asset 44.svg" class="img-fluid rounded-top" id="logo" alt="">
{% if mesage is defined and mesage %}
<div class="alert alert-warning">{{ mesage }}</div>
{% endif %}
<h1>Login</h1>
<!-- 修正表单action为对应login路由函数 -->
<form action="{{ url_for('login') }}" method="post">
    <div class="txt_field">
        <input type="text" name="username" id="username" required>
        <span></span>
        <label for="username">Username</label>
    </div>
    <div class="txt_field">
        <input type="password" name="password" id="password" required>
        <span></span>
        <label for="password">Password</label>
    </div>
    <div class="pass">Forgot Password?</div>
    <input type="submit" value="Login">
    <div class="signup_link">
        Not a member? <a href="{{ url_for('register') }}">Daftar</a>
    </div>
</form>

额外注意事项

  • 确保已导入Flask所需模块:from flask import Flask, render_template, request, redirect, url_for, session
  • 验证MySQL连接配置正确,user表已存在且包含username、password、email字段
  • 若需更灵活的消息传递,可使用Flask的flash功能,需在模板中添加get_flashed_messages()的处理逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 02:25:24