好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

今天用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项目,总要被编码问题折腾几下,这次也不例外。结果网上一搜,也没搜出解决方法,倒是相关错误有人给出页面顶部加上编码设置:

这有点要命,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内容居然报编码错误!!_自学的详细内容...

  阅读:38次