Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModuleNotFoundError: No module named 'MySQLdb' Amazon MySQL RDS SQLAlchemy

I am having issues with connecting Amazon AWS MySQL with SQLAlchemy. According to the instruction, I have connected.

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://<user>:<password>@<host>/<dbname>

But there is an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/ec2-user/venv/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 514, in __get__
    return type.query_class(mapper, session=self.sa.session())
  File "/home/ec2-user/venv/lib/python3.7/site-packages/sqlalchemy/orm/scoping.py", line 74, in __call__
    return self.registry()
  File "/home/ec2-user/venv/lib/python3.7/site-packages/sqlalchemy/util/_collections.py", line 1001, in __call__
    return self.registry.setdefault(key, self.createfunc())
  File "/home/ec2-user/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 2950, in __call__
    return self.class_(**local_kw)
  File "/home/ec2-user/venv/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 143, in __init__
    bind = options.pop('bind', None) or db.engine
  File "/home/ec2-user/venv/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 877, in engine
    return self.get_engine()
  File "/home/ec2-user/venv/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 896, in get_engine
    return connector.get_engine()
  File "/home/ec2-user/venv/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 559, in get_engine
    self._engine = rv = sqlalchemy.create_engine(info, **options)
  File "/home/ec2-user/venv/lib/python3.7/site-packages/sqlalchemy/engine/__init__.py", line 424, in create_engine
    return strategy.create(*args, **kwargs)
  File "/home/ec2-user/venv/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 81, in create
    dbapi = dialect_cls.dbapi(**dbapi_args)
  File "/home/ec2-user/venv/lib/python3.7/site-packages/sqlalchemy/dialects/mysql/mysqldb.py", line 102, in dbapi
    return __import__('MySQLdb')
ModuleNotFoundError: No module named 'MySQLdb'

I am using Python3.7 version. Even according to the stackoverflow, I have installed pymysql, but still facing the problem.

Thank you for your reply.

like image 773
3Mcollab Avatar asked Jan 27 '23 16:01

3Mcollab


2 Answers

If you use the PyMySQL client to connect to MySQL, your SQLAlchemy connection string needs to start with

 mysql+pymysql://

instead of mysql://.

If you connect with mysql:// then you will need to install the MySQLdb library as shown in the Traceback.

like image 165
Matt Healy Avatar answered Jan 31 '23 22:01

Matt Healy


Above issues has been solved with the following:

import pymysql

pymysql.install_as_MySQLdb()

Nothing to change anywhere.

like image 27
3Mcollab Avatar answered Jan 31 '23 21:01

3Mcollab