Django 1.5+pymysql错误:ImportError:无法导入name Thing2Li

2024-06-16 12:50:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用django1.5和pymysql作为MySQLdb,就像这里的How to make Django work with unsupported MySQL drivers such as gevent-mysql or Concurrence's MySQL driver?

在我的管理命令中:

+try:
+    import pymysql
+    pymysql.install_as_MySQLdb()
+except ImportError:
+    pass 

但是得到错误:

^{pr2}$

如何修复?在


Tags: todjangomakeaswithmysqlgeventhow
2条回答

MySQLdb中,如果使用的是MySQL的最新版本,则不会使用^{}方法,在这种情况下,当连接可用时,将使用连接的^{}方法。在

您需要对pymysql进行修补,以便它执行相同的操作,并允许您使用连接的方法。在

上下文

此方法用于转义SQL语句。因此,你必须考虑安全问题。在

之所以要使用连接的方法是字符集,它在转义中起作用。在

修复ImportError

这是一个非常简单的方法,您只需要在^{}中实现一个伪Thing2Literal方法。我们永远不会叫它安威,所以我们不在乎它:

def _Thing2Literal(o,d):
    """
    Implemented for compatibility with Django.
    This function is overriden by the connection's escape method when one is available.
    """
    raise NotImplementedError('Thing2Literal is only implemented through the Connection object.')

 Thing2Literal = _Thing2Literal

当连接可用时在运行时修补Thing2Literal

pymysql.connections.Connection中,添加:import pymysql.converters

pymysql.connections.Connection.__init__末尾,添加以下内容:

^{pr2}$

pymysql.connections.Connection.__del__的末尾,加上反面:

pymysql.converters.Thing2Literal = pymysql.converters._Thing2Literal

我们可以放弃d参数,因为它是现有转换的字典,Connection.escape方法已经可以使用它。在

注意事项

这很可能会被破坏,并暴露安全问题。
另外,我很确定如果你有几个活动连接使用不同的字符集,它会严重中断。在


您可能还需要对Django进行一些修改,以确保它在可用时使用您的monkey补丁版本,即用仍然将Thing2Literal名称绑定到模块的东西来替换{}。在

当然,无需修补django并使_Thing2Literal函数更智能,也可以达到相同的效果。在

刚刚在Django 1.5.1和PyMySQL 0.5上遇到了相同的问题

通过使用PyMySQL的CMGS fork(https://github.com/CMGS/PyMySQL)修复。希望它能进入主线PyMySQL。在这里查看CMGS的请求:https://github.com/petehunt/PyMySQL/pull/106

从作者的评论和pull请求中的反馈来看,我认为它对于生产用途来说非常可靠。在

示例要求.txt线路: -egit://github.com/CMGS/PyMySQL.git\egg=PyMySQL开发

相关问题 更多 >