解决django使用logging时“character mapping must return integer, None or unicode”错误
今天调试Django项目时候,使用Logging记录异常并发送邮件给网站管理人员,测试时候始终报错:
Traceback (most recent call last):
File "/usr/lib64/python2.7/wsgiref/handlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "/home/xsy/.virtualenvs/dz_pro/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 177, in __call__
response = self.get_response(request)
File "/home/xsy/.virtualenvs/dz_pro/lib/python2.7/site-packages/django/core/handlers/base.py", line 230, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/home/xsy/.virtualenvs/dz_pro/lib/python2.7/site-packages/django/core/handlers/base.py", line 284, in handle_uncaught_exception
'request': request
File "/usr/lib64/python2.7/logging/__init__.py", line 1185, in error
self._log(ERROR, msg, args, **kwargs)
File "/usr/lib64/python2.7/logging/__init__.py", line 1278, in _log
self.handle(record)
File "/usr/lib64/python2.7/logging/__init__.py", line 1288, in handle
self.callHandlers(record)
File "/usr/lib64/python2.7/logging/__init__.py", line 1328, in callHandlers
hdlr.handle(record)
File "/usr/lib64/python2.7/logging/__init__.py", line 751, in handle
self.emit(record)
File "/home/xsy/.virtualenvs/dz_pro/lib/python2.7/site-packages/django/utils/log.py", line 117, in emit
self.send_mail(subject, message, fail_silently=True, html_message=html_message)
File "/home/xsy/.virtualenvs/dz_pro/lib/python2.7/site-packages/django/utils/log.py", line 120, in send_mail
mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs)
File "/home/xsy/.virtualenvs/dz_pro/lib/python2.7/site-packages/django/core/mail/__init__.py", line 97, in mail_admins
mail.send(fail_silently=fail_silently)
File "/home/xsy/.virtualenvs/dz_pro/lib/python2.7/site-packages/django/core/mail/message.py", line 292, in send
return self.get_connection(fail_silently).send_messages([self])
File "/home/xsy/.virtualenvs/dz_pro/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 100, in send_messages
new_conn_created = self.open()
File "/home/xsy/.virtualenvs/dz_pro/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 67, in open
self.connection.login(self.username, self.password)
File "/usr/lib64/python2.7/smtplib.py", line 607, in login
(code, resp) = self.docmd(encode_cram_md5(resp, user, password))
File "/usr/lib64/python2.7/smtplib.py", line 571, in encode_cram_md5
response = user + " " + hmac.HMAC(password, challenge).hexdigest()
File "/usr/lib64/python2.7/hmac.py", line 78, in __init__
self.outer.update(key.translate(trans_5C))
TypeError: character mapping must return integer, None or unicode
根据错误提示,追进了hmac.py中看了源码,发现key其实就是一个字符串,是配置在settings中的EMAIL_HOST_USER以及EMAIL_HOST_PASSWORD,而translate函数则是根据给出的参数表将字符串进行映射加密的,而且是最简单的凯撒加密法。