Mac下Django项目Did you install mysqlclient/Error loading MySQLdb module报错解决方法

MacOs 10.14.6下Django项目Did you install mysqlclient报错解决方法
现象 启动项目报错:

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient?

首先确保mysql安装并且配置正确
这个PATH是为了pip安装mysqlclient时能读取到mysql_config变量,否则会报找不到mysql_config的错
vim ~/.bash_profile # mysql export PATH="$PATH":/usr/local/mysql/bin/ alias mysql='/usr/local/mysql/bin/mysql' alias mysqladmin='/usr/local/mysql/bin/mysqladmin' alias mysqldump='/usr/local/mysql/bin/mysqldump'

卸载mysqlclient
pip uninstall mysqlclient

安装mysql-connector-c
brew install mysql-connector-c

由于mysql-connector-c依赖openssl,会自动安装openssl
brew info openssl

得到
If you need to have openssl first in your PATH run: echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile For compilers to find openssl you may need to set: export LDFLAGS="-L/usr/local/opt/openssl/lib" export CPPFLAGS="-I/usr/local/opt/openssl/include"

将openssl环境变量输出到当前bash环境配置中即.bash_profile或者.zshrc
建议修改bash_profile,在zsh中source bash_profile来加载其他配置
cat >> ~/.bash_profile <> ~/.bash_profile

【Mac下Django项目Did you install mysqlclient/Error loading MySQLdb module报错解决方法】由于前面配置过mysql,执行which mysql_config,终端输出
/usr/local/bin/mysql_config

修改mysql_config源文件,在里面找到如下内容
# Create options libs="-L$pkglibdir" libs="$libs -l " 将他替换成 # Create options libs="-L$pkglibdir" libs="$libs -lmysqlclient -lssl -lcrypto"

最后重新加载环境变量并重新安装
source ~/.bash_profile pip install mysqlclient==1.4.2.post1

补充:
可能还是会遇到安装失败,那么直接pip install mysqlclient不指定版本

    推荐阅读