【问题标题】:variable is undefined flask mysql变量是未定义的烧瓶mysql
【发布时间】:2020-09-24 22:47:17
【问题描述】:

我需要在页面上问候用户。 F.ex:您好 {{ name }},但我收到错误 UnboundLocalError: local variable 'account' referenced before assignment。下面的代码有什么问题?

python:

app = Flask(__name__)

mysql = MySQL(app)


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        cur = mysql.connection.cursor()
        cur.execute('INSERT INTO users(name, email) VALUES(%s, %s)', (name, email))
        mysql.connection.commit()
        cur.close()
        return redirect('profile')

    return render_template('index.html')


@app.route('/profile', methods=['GET'])
def profile():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        cur = mysql.connection.cursor()
        cur.execute('SELECT * FROM users')

        account = cur.fetchone()

    return render_template('profile.html', account=account)

index.html:

<form action="" method="POST">
    <span style="color: #fff;">Firstname:</span><input type="text" name="name" placeholder="Type your firstname"><br><br>
    <input type="submit" name="submit" value="submit">
</form>

profile.html

<h4 style="color: #fff;">Your firstname: is {{ account['name'] }}</h4>
<h4 style="color: #fff;">Your email: is {{ account['email'] }}</h4>

我可以连接到数据库并获取用户数据,但在 profile.html 页面上我收到错误 如何解决?请帮忙。

【问题讨论】:

标签: python mysql flask


【解决方案1】:

您尚未将帐户传递给模板。

而不是,

return render_template('profile.html')

你需要写成,

return render_template('profile.html', account=account)

编辑:

@app.route('/profile', methods=['GET','POST'])
def profile():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        cur = mysql.connection.cursor()
        cur.execute('SELECT * FROM users')

        account = cur.fetchone()

        return render_template('profile.html', account=account)

或者,如果您希望配置文件成为获取请求,您可以这样做

@app.route('/profile', methods=['GET','POST'])
def profile():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
    cur = mysql.connection.cursor()
    cur.execute('SELECT * FROM users')

    account = cur.fetchone()

    return render_template('profile.html', account=account)

【讨论】:

  • 现在我收到此错误UnboundLocalError: local variable 'account' referenced before assignment
  • 你能在我编辑答案时更正缩进吗:)
  • 并确保在路由中也启用 POST 方法。
  • 现在我得到了这个错误The view function did not return a valid response. The function either returned None or ended without a return statement. 它没有看到 profile.html。
  • 检查最新编辑 :) 我不知道您正在检查 GET 请求。立即尝试。
猜你喜欢
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-28
  • 2020-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多