Django SQL Logging as UTF-8 : avoiding UnicodeDecodeError while settings.DEBUG=True

牧云@^-^@ 提交于 2021-01-29 03:15:14

问题


For a long time, I've had to struggle with a "UnicodeDecodeError:ascii codec can't decode..." error while save()-ing a model, until I "accidentally" set settings.DEBUG=False. I realized then that the Unicode exception was not from my data nor from my code, but from Django's SQL logging, which is apparently in ascii.

Question is, is there an easy way to convert the logging from ascii to utf-8, so that I can still avail of the logging feature without dealing with the exception?

Many thanks! =)


回答1:


I found a hack which seems to work for the time being. In django/db/backends/util.py:

class CursorDebugWrapper(CursorWrapper):

    # XXX callproc isn't instrumented at this time.

    def execute(self, sql, params=None):
        start = time()
        try:
            return super(CursorDebugWrapper, self).execute(sql, params)
        finally: 
            stop = time()
            duration = stop - start
            sql = self.db.ops.last_executed_query(self.cursor, sql, params)
            self.db.queries.append({
                'sql': sql,
                'time': "%.3f" % duration,
             })
            logger.debug('(%.3f) %s; args=%s' % (duration, sql, params),
                extra={'duration': duration, 'sql': sql, 'params': params}
            )

I changed the last line to:

            logger.debug('(%.3f) %s; args=%s' % (duration, sql.decode('utf-8'), params),
                extra={'duration': duration, 'sql': sql, 'params': params}
            )

Would be great if someone could give a better / more elegant solution.



来源:https://stackoverflow.com/questions/22800697/django-sql-logging-as-utf-8-avoiding-unicodedecodeerror-while-settings-debug-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!