码迷,mamicode.com
首页 > Web开发 > 详细

Print to the console in django without UnicodeEncodeErrors

时间:2015-01-08 17:25:22      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

在线下环境的时候,正常运行,然后当线上环境,添加汉字报了如下的bug:

1 Traceback (most recent call last):  
2 File "views.py", line 107, in <module>
3     print kwargs
4 UnicodeEncodeError: ascii codec cant 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. 

 

Print to the console in django without UnicodeEncodeErrors

标签:

原文地址:http://www.cnblogs.com/smallc/p/4210907.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!