当前位置:Gxlcms > 数据库问题 > Django2.X 与 PyMySQL包兼容

Django2.X 与 PyMySQL包兼容

时间:2021-07-01 10:21:17 帮助过:21人阅读



要求mysqlclient需要1.3.13版本及之后新版本

 

其中
mysqlclient 是python与mysql数据库链接的一个包, 由C语言编写.
pymysql 是纯 python编写的与mysql数据链接的包.速度上可能稍逊一筹, 但胜在安装使用方便简洁.

两包功能相似, 使用方法雷同.

此处错误原因是因为django框架(2.2)默认使用链接的包是mysqlclient, 而不是pymysql.并且在2.2中把MySQL使用force_str返回为str.
        
        Django2.2源码:

    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.
        # MySQLdb returns string, PyMySQL bytes.
        return force_str(getattr(cursor, ‘_executed‘, None), errors=‘replace‘)


解决办法三种:

1. 使用mysql-client替代pymysql, 来连接python与mysql.

2. 更改django源码, 注释掉对mysqlclient版本的判断,
如出现错误代码,AttributeError: ‘str‘ object has no attribute ‘decode‘.
则在对应报错位置:
.decode改为.encode
或者

导入

from django.utils.encoding import force_str

使用django自带的force_str来转化

3. 当然, 还有回退也是一个解决此问题的方法, 回退Django框架至2.2之前(2.1.4或更早)

Django2.X 与 PyMySQL包兼容

标签:源码   mysql数据库   版本   框架   span   string   ret   功能   encoding   

人气教程排行