Search code examples
pythonmysqlflaskflask-mysql

I have a problem with sql query don´t work in flask


i try to run that code but i have problems with the sql query, but if run the query in mysql workbeck it works

app.config['MYSQL_HOST'] = "localhost"
app.config['MYSQL_USER'] = "root"
app.config['MYSQL_PASSWORD'] = ""
app.config['MYSQL_DB'] = "inventario_bodega"
mysql = MySQL(app)

@app.route("/login", methods=["POST"])
def login():
    try:
        data = request.json
        user = data["user"]
        password = data["password"]
        cur = mysql.connection.cursor()
        #thats part don´t work
        cur.execute("SELECT * FROM usuarios WHERE usuario = %s", (user))

        data = cur.fetchone()
        cur.close()
        if(not (data == [])):
            if(data[6] == password):
                encoded_jwt = jwt.encode(
                    {'datos': data}, app.config['SECRET_KEY'], algorithm='HS256')
                return encoded_jwt, 200
            else:
                return "Usuario y/o Contraseña incorrecta", 401
        else:
            return "Usuario y/o Contraseña incorrecta", 401
    except:
        return "Error al iniciar sesion", 500

but don´t show me a error only show me a 500 error

this is what appears to me in the terminal


Solution

  • cur.exectute() wants a tuple or list of arguments. It looks like you're trying for the former, which is one of those edge cases in Python where the comma distinguishes between parenthesis used to form a tuple or parenthesis used to control order of evaluation.

    Change

    cur.execute("SELECT * FROM usuarios WHERE usuario = %s", (user))
    

    to

    cur.execute("SELECT * FROM usuarios WHERE usuario = %s", (user,))