我試圖創建一個簡單的webapp。並在此期間從調試器中裁剪出上述錯誤。任何人都可以幫助我。其他一切正常工作,數據庫服務器正常工作。但在這裏無法找出問題。UnboundLocalError:賦值之前引用的局部變量'cursor'(第72行)
from flask import Flask, render_template, json, request
from flask.ext.mysql import MySQL
from werkzeug import generate_password_hash, check_password_hash
app = Flask(__name__)
mysql = MySQL()
app = Flask(__name__)
app.secret_key = 'why would I tell you my secret key?'
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'mydata'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
@app.route("/")
def main():
return render_template('login.html')
@app.route('/showSignUp')
def showSignUp():
return render_template('signup.html')
@app.route('/userHome')
def userHome():
if session.get('user'):
return render_template('userHome.html')
else:
return render_template('error.html',error = 'Unauthorized Access')
@app.route('/logout')
def logout():
session.pop('user',None)
return redirect('/')
@app.route('/putemail')
def putemail():
return render_template('putemail.html')
@app.route('/validateLogin', methods=['POST','GET'])
def validateLogin():
try:
_username = request.form['inputusername']
_password = request.form['inputpassword']
con = mysql.connect()
cursor = con.cursor()
cursor.callproc('sp_validateLogin',(_username,))
data = cursor.fetchall()
if len(data) > 0:
if check_password_hash(str(data[0][4]),_password):
session['user'] = data[0][0]
return redirect('/userHome')
else:
return render_template('error.html',error = 'Wrong Email address or Password.')
else:
return render_template('error.html',error = 'Wrong Email address or Password.')
except Exception as e:
return render_template('error.html',error=str(e))
finally:
cursor.close()
con.close()
@app.route('/signUp', methods=['POST','GET'])
def signUp():
try:
# read the posted values from the UI
_name = request.form['inputfullname']
_username = request.form['inputusername']
_email = request.form['inputemail']
_password = request.form['inputpassword']
# validate the received values
if _name and _username and _email and _password:
# All Good, let's call MySQL
conn = mysql.connect()
cursor = conn.cursor()
_hashed_password = generate_password_hash(_password)
cursor.callproc('sp_createUser', (_name,_username,_email,_hashed_password))
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
return json.dumps({'message':'User created successfully !'})
else:
return json.dumps({'error':str(data[0])})
else:
return json.dumps({'html':'<span>Enter the required fields</span>'})
except Exception as e:
return json.dumps({'error':str(e)})
finally:
cursor.close()
conn.close()
if __name__ == "__main__":
app.debug = True
app.run()
請確保您準確地發佈了您的縮進,否則您的Python代碼將毫無意義。 – khelwood
哦!對不起,現在用正確的縮進重新編輯了這篇文章。 @khelwood –
請[edit]包含[mcve]。 – davidism