user123 user123 - 1 month ago 19
MySQL Question

Python NameError, global name not defined

I am following this tutorial to create a Python 2.7 and Flask web app with a MySQL database.

Why am I getting this error on

_password
?

app.py


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

# create the app
app = Flask(__name__)

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

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

@app.route("/signUp", methods=["POST"])
def signUp():
# read the values input by the user
global _name, _email, _password
_name = request.form["inputName"]
_email = request.form["inputEmail"]
_password = request.form["inputPassword"]

# validate inputs
if _name and _email and _password:
return json.dumps({"html":"<span>fields are good</span>"})
else:
return json.dumps({"html":"<span>enter required fields</span>"})

# MySQL configurations
app.config["MYSQL_DATABASE_USER"] = "root"
app.config["MYSQL_DATABASE_PASSWORD"] = ""
app.config["MYSQL_DATABASE_DB"] = "NotesList"
app.config["MYSQL_DATABASE_HOST"] = "localhost"
MySQL().init_app(app)

def connectDB():
conn = mysql.connect()
cursor = conn.cursor()

_hashed_password = generate_password_hash(_password)

cursor.callproc("sp_createUser", (_name, _email, _hashed_password))

def check():
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
return json.dumps({"message":"user created"})
else:
return json.dumps({"error":str(data[0])})

app.debug = True
if __name__ == "__main__":
app.run()

Answer

The reason is that the app can't be instantiated because you're calling upon names that haven't been created yet. It's almost NEVER a good idea to use global to move variables into the global scope. Don't do that.

Even if you decided you don't care about best-practices, the variables won't get into the global scope until the function is actually called, which never happens before those variables are being used in your code.

You should make your db connection before the request. You'll probably want to utilize the before_request decorator to do this, storing the connection in g -- see the database connection portion of the Flaskr tutorial for more info.

Then put the parts of the code that work with the database INSIDE of the route function. The way your code is written write now, you're executing those lines EVERY time your app gets instantiated, not just when someone uses the view /signup

Comments