django源码bug解决方案

    File "D:\tool\python\virtualenv\xxx\lib\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'

1 修改源码

# 点到最后一条报错信息的路径
# 将query = query.decode(errors='replace')中的decode改为encode

2 修改配置

debug为False时django项目能正常使用

DEBUG = True
# DEBUG = False

3 猴子补丁

在django项目入口处:manage.py中加入猴子补丁

替换报错的函数

def monkey_patch_last_executed_query():
    def last_executed_query(self, cursor, sql, params):
        query = getattr(cursor, '_executed', None)
        if query is not None:
            query = query.encode(errors='replace')
        return query
    DatabaseOperations.last_executed_query = last_executed_query
import os
import sys

from django.db.backends.mysql.operations import DatabaseOperations


def monkey_patch_last_executed_query():
    def last_executed_query(self, cursor, sql, params):
        query = getattr(cursor, '_executed', None)
        if query is not None:
            query = query.encode(errors='replace')
        return query
    DatabaseOperations.last_executed_query = last_executed_query


def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'xxx.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc

    monkey_patch_last_executed_query()
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()

 posted on 2020-12-15 17:42  wwwpy  阅读(115)  评论(0编辑  收藏  举报