【发布时间】: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 页面上我收到错误
如何解决?请帮忙。
【问题讨论】:
-
你试过搜索引擎吗?真的很棒。 stackoverflow.com/questions/9845102/using-mysql-in-flask
-
@Hoppo,你能再检查一下这个问题吗?