Print to the console in django without UnicodeEncodeErrors
在线下环境的时候,正常运行,然后当线上环境,添加汉字报了如下的bug:
1 Traceback (most recent call last): 2 File "views.py", line 107, in <module> 3 print kwargs 4 UnicodeEncodeError: ‘ascii‘ codec can‘t encode character u‘\xa0‘ in position 20: ordinal not in range(128)
猜测应该是线上环境经过uwsgi的时候出了问题,然后去搜uwsgi django UnicodeEncodeError
得到类似的答案:
http://stackoverflow.com/questions/24887929/locale-on-django-and-uwsgi-unicodeencodeerror
http://chase-seibert.github.io/blog/2014/01/12/python-unicode-console-output.html
看了两篇文章后找到两种解决方案:
1.在uwsgi文件中添加如下配置
env = PYTHONIOENCODING=UTF-8
2.在django的settings.py文件中加入
import sys import codecs sys.stdout = codecs.getwriter(‘utf8‘)(sys.stdout) sys.stderr = codecs.getwriter(‘utf8‘)(sys.stderr)
以上两种方案经尝试后都解决了那个该bug。
总结:Your termianl can typically handle UTF8 characters just fine. The issue is actually that Python is just getting confused about what encoding the terminal accepts.
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。