No module named 'MySQLdb',但无法pip安装(并且这不是pip的问题)
No module named 'MySQLdb',但无法pip安装(并且这不是pip的问题)
当我尝试使用我的Flask应用程序进行POST数据时,出现了错误。\n这是我的SQLAlchemy类,有3个字段和相应的模式类:\n
class Plant(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100)) dur = db.Column(db.Integer) def __init__(self, name, dur): self.name = name self.dur = dur class PlantSchema(ma.SQLAlchemySchema): class Meta: model = Plant
\n这是在app.py中的POST请求,以便将植物模型添加到我的数据库中:\n
plant_schema = PlantSchema() @app.route('/plants', methods=['POST']) def add_plant(): name = request.json.get('name', '') dur = request.json.get('dur', '') plant = Plant(name=name, dur=dur) db.session.add(plant) db.session.commit() return plant_schema.jsonify(plant)
\n不幸的是,当我在Postman中进行POST请求时,我得到了以下错误:\n
ModuleNotFoundError: No module named 'MySQLdb' ...
\n当我尝试pip install mysqlclient
(这是推荐的解决方法)时,我得到了以下错误:\n
Collecting mysqlclient Using cached mysqlclient-2.1.0.tar.gz (87 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: mysql_config: command not found /bin/sh: mariadb_config: command not found /bin/sh: mysql_config: command not found Traceback (most recent call last): File "", line 2, in File " ", line 34, in File "/private/var/folders/j5/b194wjbn32sbqct7crpvcp2w0000gn/T/pip-install-ijejonzz/mysqlclient_841539cf1eed4511a135f8e95cb2be75/setup.py", line 15, in metadata, options = get_config() File "/private/var/folders/j5/b194wjbn32sbqct7crpvcp2w0000gn/T/pip-install-ijejonzz/mysqlclient_841539cf1eed4511a135f8e95cb2be75/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/private/var/folders/j5/b194wjbn32sbqct7crpvcp2w0000gn/T/pip-install-ijejonzz/mysqlclient_841539cf1eed4511a135f8e95cb2be75/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed
\n如果问题不是由pip引起的,我不确定还有什么其他尝试的方法?
在使用Python进行MySQL操作时,出现了"No module named 'MySQLdb'"的错误,但是无法通过pip install命令进行安装(而且这并不是pip的问题)。产生此问题的原因是缺少MySQL客户端开发库。安装程序无法在系统上找到所需的可执行文件mysql_config。
解决方法如下:
Ubuntu
sudo apt install libmysqlclient-dev
CentOS
sudo yum install mariadb-devel
以上命令将安装所需的MySQL客户端开发库。安装完成后,再次运行Python脚本即可成功导入MySQLdb模块,解决"No module named 'MySQLdb'"的错误。