Julian Julian - 1 month ago 13
Python Question

Flask Python Registration doesn't work properly

I have this register form on my flask webapp, which checks if an username is already registered or not. For some reason when I register, it redirects me to my home.html (Which means im logged in), and also gives me a

flash("Error. Username already exists")
back. Why does it go into the
except:
and then in the
finally
? I'm not quite sure how to fix that. I've checked my database as well. My user information is saved on there.

Thats my code:

if request.method == "POST":
with sql.connect(DATABASE) as con:
cur = con.cursor()
try:
# flash("register attempted")

username = request.form['username']
password = pwd_context.encrypt((str(request.form['password'])))
email = request.form['email']

cur.execute("INSERT INTO users (name,password,email) VALUES (?,?,?)",(username,password,email) )
con.commit()
flash ("Successfully registrated")
except:
con.rollback()
flash("Error. Username already exists")
return redirect(url_for("register"))

finally:
session['logged_in'] = True
session['username'] = username
gc.collect()
return render_template("home.html")
con.close()


EDIT:

x = cur.execute("SELECT * FROM users WHERE username = ?"),(username)

if int(len(x)) > 0:
flash("Error. Username already exists")
return redirect(url_for("register"))
else:
cur.execute("INSERT INTO users (name,password,email) VALUES (?,?,?)", (username, password, email))
con.commit()
flash("Successfully registrated")
session['logged_in'] = True
session['username'] = username
gc.collect()
msg = Message('Hello', sender='yourId@gmail.com', recipients=[email])
msg.body = "your username for ak047 is: %s and your password is %s" % (request.form['username'],request.form['passwordd'])
mail.send(msg)
return render_template("home.html", msg=msg)
con.close()

Answer

You are not catching any particular exception. If your code inside your try block throws any exception, for example that request.form['email'] was null and you tried to insert it into a non-null column, it would throw an exception that would cause your code in the except block to run. Even an IndexError would cause this to run. So any error will result in the flash("Error. Username already exists") line to execute.

The code in the finally block will always run.

Have a look at error handling in Python. In particular on catching specific errors. It is a very useful thing to get right.

If you want to know exactly what exception is being thrown, you could do something like:

try:
    ....
except Exception as e:
    print(e)
    ....

This catches any exception and stores the exception and thusly the stack trace in the variable e, ready to be printed out or logged to stdout.

Once you know that your code is, for example, throwing an IndexError, or a NotNull error, or whatever error it might be, you can write error specific code to launch depending on the error, for example:

try:
    ....
except IndexError:
    # Do some code if there is an IndexError in the try block
except NotNull:
    # Do some code if your db throws a not null error when trying to insert something in the try block
finally:
    # Always run the code in here...
Comments