Mysql query error with config.py file

Hello
I get the following error when I launch the query to mysql

Traceback (most recent call last):
  File "/root/myproject/models/ModelUser.py", line 9, in login
    cursor = db.connection.cursor()
  File "/root/myproject/myprojectenv/lib/python3.10/site-packages/flask_mysqldb/__init__.py", line 101, in connection
    ctx.mysql_db = self.connect
  File "/root/myproject/myprojectenv/lib/python3.10/site-packages/flask_mysqldb/__init__.py", line 88, in connect
    return MySQLdb.connect(**kwargs)
  File "/root/myproject/myprojectenv/lib/python3.10/site-packages/MySQLdb/__init__.py", line 123, in Connect
    return Connection(*args, **kwargs)
  File "/root/myproject/myprojectenv/lib/python3.10/site-packages/MySQLdb/connections.py", line 185, in __init__
    super().__init__(*args, **kwargs2)
MySQLdb.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: NO)")

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/root/myproject/myprojectenv/lib/python3.10/site-packages/flask/app.py", line 2190, in wsgi_app
    response = self.full_dispatch_request()
  File "/root/myproject/myprojectenv/lib/python3.10/site-packages/flask/app.py", line 1486, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/root/myproject/myprojectenv/lib/python3.10/site-packages/flask/app.py", line 1484, in full_dispatch_request
    rv = self.dispatch_request()
  File "/root/myproject/myprojectenv/lib/python3.10/site-packages/flask/app.py", line 1469, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/root/myproject/myproject.py", line 50, in login
    logged_user=ModelUser.login(db,user)
  File "/root/myproject/models/ModelUser.py", line 20, in login
    raise Exception(ex)
Exception: (1045, "Access denied for user 'root'@'localhost' (using password: NO)")

my app.py where it launches is

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method=='POST':
        user = User(0,request.form['username'],request.form['password'])
        logged_user=ModelUser.login(db,user)
        if logged_user != None:
            if logged_user.password:
                login_user(logged_user)
                return redirect(url_for('home'))
            else:
                flash("invalid password")
                return render_template('auth/login.html')
        else:
            flash("User not found")
            return render_template('auth/login.html')
    else:
        return render_template('auth/login.html')

and I launch the query with

class ModelUser():

    @classmethod
    def login(self, db, user):
        try:
            cursor = db.connection.cursor()
            sql = """SELECT id, username, password, fullname FROM user 
                    WHERE username = '{}'""".format(user.username)
            cursor.execute(sql)
            row = cursor.fetchone()
            if row != None:
                user = User(row[0], row[1], User.check_password(row[2], user.password), row[3])
                return user
            else:
                return None
        except Exception as ex:
            raise Exception(ex)
        
    @classmethod
    def get_by_id(self, db, id):
        try:
            cursor = db.connection.cursor()
            sql = "SELECT id, username, fullname FROM user WHERE id = {}".format(id)
            cursor.execute(sql)
            row = cursor.fetchone()
            if row != None:
                return User(row[0], row[1], None, row[2])
            else:
                return None
        except Exception as ex:
            raise Exception(ex)

I also have a config.py file

class Config:
    SECRET_KEY = '456fghfghfggfg5'

class DevelopmentConfig(Config):
    DEBUG = True
    MYSQL_HOST = 'localhost'
    MYSQL_USER = 'root'
    MYSQL_PASSWORD = '*********'
    MYSQL_DB = 'xxxxx'


config = {
    'development': DevelopmentConfig
}

in my app.py file I also have

db = MySQL(app)
login_manager_app=LoginManager(app)

@login_manager_app.user_loader
def load_user(id):
    return ModelUser.get_by_id(db,id)

I can’t answer your question, but I notice that you’re building queries with string formatting. That’s a bad idea because it can leave the database open to “SQL Injection”.

The correct way is to use a parameterised query.

For example, instead of:

sql = """SELECT id, username, password, fullname FROM user 
        WHERE username = '{}'""".format(user.username)
cursor.execute(sql)

you should do:

sql = """SELECT id, username, password, fullname FROM user 
        WHERE username = %s"""
cursor.execute(sql, (user.username,))

The %s in the query string is a placeholder for the value. The database engine will do any substitution itself, safely.

1 Like

Thank you very much for the contribution, I will modify the query as indicated.