问题
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