UnboundLocalError:赋值之前引用的局部变量“游标” [英] UnboundLocalError: local variable 'cursor' referenced before assignment

查看:595
本文介绍了UnboundLocalError:赋值之前引用的局部变量“游标”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我是一个新手,但工作在注册系统形式在flask / MYSQL

我收到此错误(UnboundLocalError:局部变量光标之前引用)

经过数小时的代码和研究之后,我需要你的帮助。

这是我的文件,请让我知道如果我还有其他事情需要分享。
谢谢

  from flask import Flask,render_template,json,从flask.ext.mysqldb请求
从werkzeug导入MySQL
导入generate_password_hash,check_password_hash
$ b app = Flask(__ name__)
mysql = MySQL()


app.config ['MYSQL_DATABASE_USER'] ='x'
app.config ['MYSQL_DATABASE_PASSWORD'] ='x'
app.config ['MYSQL_DATABASE_DB'] ='x'
app.config [ MYSQL_DATABASE_HOST'] ='x'
mysql.init_app(app)
$ b $ app_route('/')
def main():
return render_template 'index.html')

@ app.route('/ login')
def login():
return render_template('login.html')

@ app.route('/ showSignUp')
def showSignUp():
return render_template('signup.html')


@app .route('/ signUp',methods = ['POST','GET'])
def signUp():
try:
_name = request.form ['inputName']
_email = request.form ['inputEmail']
_password = request.form ['inputPassword']

#验证收到的值
如果_name和_email和_password:

#所有好的,让我们调用MySQL

conn = mysql.connect()
cursor = conn.cursor()
_hashed_pa​​ssword = generate_password_hash(_password)
cursor.callproc('sp_createUser',(_ name,_email,_hashed_pa​​ssword))
data = cursor.fetchall()

如果len(data)是0:
$ conn.commit()
return json.dumps({'message':'User created successfully!'})
else:
return json.dumps({'error':str ({'html':'< span>输入必填字段< / span>'))

除了例外e:
返回json.dumps({'erro r':str(e)})
finally:
cursor.close()
conn.close()

if __name__ =='__main__':
app.run()


解决方案

在if块中检查表单值时, conn cursor 如果块没有被输入,它们没有被定义,但是你仍然试图引用它们来关闭它们。如果你定义了它们,你只能在两者上调用 close 。在if块之前移动 conn = cursor = ,或移动关闭调用块。



然而,更大的问题是您误解/过度使用Flask-MySQLdb。它会自动创建连接,并在请求完成时关闭它,这也关闭了光标。只需使用文档中所述的扩展名。

  ... 
cur = mysql.connection.cursor()
cur.callproc('sp_createUser',(name,email,hashed_pa​​ssword ))
data = cur.fetchall()
...


So I am a newbie but working on a registration system form in flask/MYSQL

I am receiving this error (UnboundLocalError: local variable 'cursor' referenced before assignment)

After hours of playing with the code and research I need your help.

This is my file, please let me know if theres anything else I need to share. thank you

from flask import Flask, render_template, json, request
from flask.ext.mysqldb import MySQL
from werkzeug import generate_password_hash, check_password_hash

app = Flask(__name__)
mysql = MySQL()


app.config['MYSQL_DATABASE_USER'] = 'x'
app.config['MYSQL_DATABASE_PASSWORD'] = 'x'
app.config['MYSQL_DATABASE_DB'] = 'x'
app.config['MYSQL_DATABASE_HOST'] = 'x'
mysql.init_app(app)

@app.route('/')
def main():
    return render_template('index.html')

@app.route('/login')
def login():
    return render_template('login.html')

@app.route('/showSignUp')
def showSignUp():
    return render_template('signup.html')


@app.route('/signUp',methods=['POST','GET'])
def signUp():
    try:
        _name = request.form['inputName']
        _email = request.form['inputEmail']
        _password = request.form['inputPassword']

        # validate the received values
        if _name and _email and _password:

            # All Good, let's call the MySQL

            conn = mysql.connect()
            cursor = conn.cursor()
            _hashed_password = generate_password_hash(_password)
            cursor.callproc('sp_createUser',(_name,_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.run()

解决方案

You only define conn and cursor inside the if block checking the form values. If the block is not entered, they're not defined, but you still try to reference them to close them anyway. You should only call close on both if you've defined them. Either move conn = and cursor = to before the if block, or move the close calls to within the block.

However, the bigger problem is that you're misunderstanding/overcomplicating how to use Flask-MySQLdb. It will automatically create the connection and close it when the request is done, which also closes the cursor. Simply use the extension as described in the docs.

...
cur = mysql.connection.cursor()
cur.callproc('sp_createUser', (name, email, hashed_password))
data = cur.fetchall()
...

这篇关于UnboundLocalError:赋值之前引用的局部变量“游标”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆