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