Django1.6访问static内容居然报编码错误!!

Python 2014-03-21 Django,编码,静态目录,setdefaultencoding

今天用Django搭建一个环境,在访问后台的时候感觉有点怪:

感觉后台页面的样式似乎没有被加载进来,于是单独打开某个样式结果浏览器提示:

A server error occurred.  Please contact the administrator.

命令行:

Traceback (most recent call last):
  File "D:\Python27\lib\wsgiref\handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "D:\Python27\lib\site-packages\django\contrib\staticfiles\handlers.py", line 68, in __call__
    return super(StaticFilesHandler, self).__call__(environ, start_response)
  File "D:\Python27\lib\site-packages\django\core\handlers\wsgi.py", line 206, in __call__
    response = self.get_response(request)
  File "D:\Python27\lib\site-packages\django\contrib\staticfiles\handlers.py", line 58, in get_response
    return self.serve(request)
  File "D:\Python27\lib\site-packages\django\contrib\staticfiles\handlers.py", line 51, in serve
    return serve(request, self.file_path(request.path), insecure=True)
  File "D:\Python27\lib\site-packages\django\contrib\staticfiles\views.py", line 41, in serve
    return static.serve(request, path, document_root=document_root, **kwargs)
  File "D:\Python27\lib\site-packages\django\views\static.py", line 61, in serve
    content_type, encoding = mimetypes.guess_type(fullpath)
  File "D:\Python27\lib\mimetypes.py", line 297, in guess_type
    init()
  File "D:\Python27\lib\mimetypes.py", line 358, in init
    db.read_windows_registry()
  File "D:\Python27\lib\mimetypes.py", line 258, in read_windows_registry
    for subkeyname in enum_types(hkcr):
  File "D:\Python27\lib\mimetypes.py", line 249, in enum_types
    ctype = ctype.encode(default_encoding) # omit in 3.x!
  File "D:\Python27\lib\encodings\utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb0 in position 1: invalid start byte

一看就知道就知道又是蛋疼的Python编码问题了,每次写Python项目,总要被编码问题折腾几下,这次也不例外。结果网上一搜,也没搜出解决方法,倒是相关错误有人给出页面顶部加上编码设置:

#encoding:utf8

这有点要命,django项目那么多文件怎么加?应该是配置里有,于是找到了相关信息并在settings.py里添加:

DEFAULT_CHARSET = 'utf-8'
FILE_CHARSET = 'utf-8'

结果还是没有解决问题,又看到有人建议用gb18030,只好把上面那两句改成

DEFAULT_CHARSET = 'gb18030'
FILE_CHARSET = 'gb18030'

问题仍旧没有解决,最后摸索了两个小时快接近崩溃边缘时,偶然我的一个设置居然把这痛苦编码问题给解决了,在manage.py添加:

reload = reload(sys) 
sys.setdefaultencoding('gb18030')

问题解决,打开css静态文件也正常响应内容了

文字链接:《Django1.6访问static内容居然报编码错误!!

文章地址:http://www.qttc.net/201403424.html

除非标注,琼台博客所有博文均为原创,转载请加文字链接注明来源

乳名?小名?昵称?网名?均可

email,放心,我不会给你乱投广告的

想获得回访就把你的站点URL写上(没有留空)

[NOTICE]木要投放广告
[NOTICE]木要骂人,说不该说的话
[NOTICE]自由言论,但要遵纪守法

Comments 4

  • 还是不行啊...要疯了...
    2014-04-27 10:31:28 [ 跟帖 ]
    检查下编辑器的编码,Python的字符编码确实愁死人,PHP都不用那么麻烦!!
    2014-04-28 09:54:40 [ 跟帖 ]
    解决了~是在mimetypes.py文件里加了 reload(sys) sys.setdefaultencoding('gb18030')
    2014-04-29 09:41:23 [ 跟帖 ]
    终于想起来,后面我也是在mimetypes.py里加入那两句代码解决的,我认为Python应该考虑中国用户多点,每次布一个项目都要花费半天去解决各种编码问题,实在蛋疼!
    2014-04-29 10:26:37 [ 跟帖 ]
    1 #