Django1.6访问static内容提示编码错误

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

full

【国内直连ChatGPT 29元起】
国内直连ChatGPT,Plus会员每月29元起,支持最新o1模型探索更多领域,无需注册OpenAI账号。

感觉页面CSS似乎没有被加载进来,于是单独访问某个CSS文件结果浏览器提示

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静态文件也正常响应内容了

full

分享

TITLE: Django1.6访问static内容提示编码错误

LINK: https://www.qttc.net/424-django-static-access.html

NOTE: 原创内容,转载请注明出自琼台博客