I’ve been struggling to implement user registration func with flask. Here is the code I’ve done.
import os from flask import Flask, render_template, flash, request, url_for, redirect, session from content_management import Content from dbconnect import connection from wtforms import Form, BooleanField, TextField, PasswordField, validators from passlib.handlers.sha2_crypt import sha256_crypt from MySQLdb import escape_string as thwart import gc def register_page(): try: form = RegistrationForm(request.form) if request.method == "POST" and form.validate(): username = form.username.data email = form.email.data password = sha256_crypt.encrypt((str(form.password.data))) c, conn = connection() x = c.execute("SELECT * FROM users WHERE username = (%s)", (thwart(username))) if int(x) > 0: flash("That username is already taken, please choose another") return render_template("register.html", form = form) else: c.execute("INSERT INTO users (username, email, password, tracking) VALUES (%s, %s, %s, %s)", (thwart(username), thwart(password), thwart(email), thwart("/introduction-to-python-programming/"))) conn.commit() flash("Thanks for registering") c.close() conn.close() gc.collect() session['login_in'] = True session['username'] = username return redirect(url_for('dashboard')) return render_template("register.html", form = form) except Exception as e: return(str(e))
When I fill the form and hit submit button, error occurs like as follows.
not all arguments converted during string formatting
I guess this happens because of thwart.
When I insert
print(thwart(username)), output b’username’.
But there is no value of int(x).
x = c.execute("SELECT * FROM users WHERE username = (%s)", (thwart(username)))
The above seems not working because of
(thwart(username)), I’m not sure.
Would you tell me how I can fix it?
To denote a tuple with a item, there should be a trailing comma before the closing parenthesis:
>>> x = (1) # without trailing command => `(1) == 1` >>> type(x) <type 'int'> >>> x = (1,) # with trailing comma >>> type(x) <type 'tuple'>
x = c.execute("SELECT * FROM users WHERE username = (%s)", (thwart(username),))
or you can use a list:
x = c.execute("SELECT * FROM users WHERE username = (%s)", [thwart(username)])