代码改变世界

114-解决mysqlclient安装失败,及django使用mysql的一个天坑

2019-08-31 14:53  lzhshn  阅读(1166)  评论(0编辑  收藏  举报

安装好MySQL之后,直接用Python进行操作是可以的,假设要在django中使用mysql,还需要安装pymysql,话不多说,直接安装:

pip3 install pymysql --user

 安装完之后,在setting进行如下配置:

 

1、首先在django工程的setting.py里,引入pymysql:

import os
import pymysql
pymysql.install_as_MySQLdb()

 

2、接着,在mysql里创建一个数据库,用来存储django里要存取的表格:

lzh@lzh-pc:~$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.17 MySQL Community Server - GPL

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> CREATE DATABASE test_app CHARACTER SET utf8;
Query OK, 1 row affected, 1 warning (0.01 sec)

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test_app           |
+--------------------+
5 rows in set (0.00 sec)

 

3、最后,配置django工程里的setting.py的database部分。其中name是在mysql里定义的某个数据库名:

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test_app',
        'USER': 'root',
        'PASSWORD': '19830427',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

 

4、高能预警!

此时无论是直接runserver,还是makemigrations,都会报错,大致是:

    raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

但是请注意,如果用pip3 list查看,是根本没有mysqlclient这个包的,一定会有人想,如果没有这个包(或者版本太低),装一下不就行了。

 

5、安装mysqlclient,官网上列举了这些前置需求:

sudo apt-get install python3-dev

sudo apt-get install default-libmysqlclient-dev

如果把这两个安装完成后,再安装mysqlclient,仍然会报错,而且会报错一整屏幕红字,非常惊悚,仔细一看,主要是这里的问题:

/usr/bin/ld: 找不到 -lssl 
/usr/bin/ld: 找不到 -lcrypto

 安装其中一个即可:sudo apt-get install libssl-dev

【注意是libssl,少一个l】

到这里,就能正常安装mysqlclient了,使用命令:pip3 install mysqlclient --user

然后再用pip3 list就能查看到:

mysqlclient           1.4.4 

到了这里,你以为问题解决了,然后能愉快地运行runserver或makemigrations?非常遗憾!

仍然会报错:django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

这就不是版本的问题了,而是它永远都会出错!!!

  File "/home/lzh/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 36, in <module>
    raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

 

 

6、大部分的人(网上看到的各种笔记,blog,经验分享)都是选择直接跳过这个错误,方法是编辑报错文件:gedit /home/yourusername/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py

将以下两行注释掉:

# if version < (1, 3, 13):
#     raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)

 

尝试运行runserver或makemigrations,仍然出错:

  File "/home/lzh/.local/lib/python3.6/site-packages/django/db/backends/mysql/operations.py", line 146, in last_executed_query
    query = query.decode(errors='replace')
AttributeError: 'str' object has no attribute 'decode'

 解决这个报错的方法是:gedit /home/lzh/.local/lib/python3.6/site-packages/django/db/backends/mysql/opetions.py

将decode改为encode,代码为:

    def last_executed_query(self, cursor, sql, params):
        # With MySQLdb, cursor objects have an (undocumented) "_executed"
        # attribute where the exact query sent to the database is saved.
        # See MySQLdb/cursors.py in the source distribution.
        query = getattr(cursor, '_executed', None)
        if query is not None:
            query = query.encode(errors='replace')
        return query

 

7、后记

安装了MySQL,然后安装了pymysql,就直接开始使用的,当报错时直接使用《6》的方法解决即可,个人怀疑是检查兼容性的代码有bug;

实际上,在bug没有解决前,费劲心思安装mysqlclient一点用处没有!

 

8、验证django使用mysql

(1)使用python3 manage.py createsuperuser创建超级管理员

(2)进入admin后台,添加一个guest:guest_name=刘振华,guest_title=先生

(3)查看mysql是否有对应内容

lzh@lzh-pc:~$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 30
Server version: 8.0.17 MySQL Community Server - GPL

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> USE test_app;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> SHOW TABLES;
+----------------------------+
| Tables_in_test_app         |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
| test_app_cnbcontent        |
| test_app_cnbtitle          |
| test_app_guestmodel        |
+----------------------------+
13 rows in set (0.00 sec)

mysql> select * from test_app_guestmodel;
+----+------------+-------------+
| id | guest_name | guest_title |
+----+------------+-------------+
|  1 | 刘振华     | 先生        |
+----+------------+-------------+
1 row in set (0.00 sec)