UnicodeDecodeError: 'utf8' codec can't decode byte 0xd5 in position 8: invalid c ontinuation byte


使用tornado 处理静态文件时出现了如下的错误

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 108: ordinal not in range(128)  

python是使用ascii作为默认编码,可以通过修改python/lib/site.py进行修改,如下所示:

def setencoding():
    """Set the string encoding used by the Unicode implementation.  The
    default is 'ascii', but if you're willing to experiment, you can
    change this."""
    encoding = "utf-8" # Default value set by _PyUnicode_Init()
    if 0:
        # Enable to support locale aware default string encodings.
        import locale
        loc = locale.getdefaultlocale()
        if loc[1]:
            encoding = loc[1]
    if 0:
        # Enable to switch off string to Unicode coercion and implicit
        # Unicode to string conversion.
        encoding = "undefined"
    if encoding != "ascii":
        # On Non-Unicode builds this will raise an AttributeError...
        sys.setdefaultencoding(encoding) # Needs Python Unicode build !

将其改为utf-8后,启动服务,访问报如下错误:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xd5 in position 8: invalid continuation byte

最后问题定位为:项目路径中包含中文,在使用

os.path.join(os.path.dirname(__file__), "static")

的时候出现了编码问题,修改即可。

关于python编码有一篇文章讲的很详细:http://blog.webforefront.com/archives/2011/02/python_ascii_co.html




免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM