2016-04-12 30 views
0

我試圖鏈接到Flask中的靜態css文件。但是,嘗試發送文件時,靜態路由會引發UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 8: ordinal not in range(128)。爲什麼我得到這個錯誤,我該如何解決?使用Flask發送靜態文件引發UnicodeDecodeError

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='content/alpin.css') }}"/> 
Traceback (most recent call last): 
    File "C:\Python27\lib\site-packages\flask-0.10.1-py2.7.egg\flask\app.py", line 1836, in __call__ 
    return self.wsgi_app(environ, start_response) 
    File "C:\Python27\lib\site-packages\flask-0.10.1-py2.7.egg\flask\app.py", line 1820, in wsgi_app 
    response = self.make_response(self.handle_exception(e)) 
    File "C:\Python27\lib\site-packages\flask-0.10.1-py2.7.egg\flask\app.py", line 1403, in handle_exception 
    reraise(exc_type, exc_value, tb) 
    File "C:\Python27\lib\site-packages\flask-0.10.1-py2.7.egg\flask\app.py", line 1817, in wsgi_app 
    response = self.full_dispatch_request() 
    File "C:\Python27\lib\site-packages\flask-0.10.1-py2.7.egg\flask\app.py", line 1477, in full_dispatch_request 
    rv = self.handle_user_exception(e) 
    File "C:\Python27\lib\site-packages\flask-0.10.1-py2.7.egg\flask\app.py", line 1381, in handle_user_exception 
    reraise(exc_type, exc_value, tb) 
    File "C:\Python27\lib\site-packages\flask-0.10.1-py2.7.egg\flask\app.py", line 1475, in full_dispatch_request 
    rv = self.dispatch_request() 
    File "C:\Python27\lib\site-packages\flask-0.10.1-py2.7.egg\flask\app.py", line 1461, in dispatch_request 
    return self.view_functions[rule.endpoint](**req.view_args) 
    File "C:\Python27\lib\site-packages\flask-0.10.1-py2.7.egg\flask\helpers.py", line 822, in send_static_file 
    cache_timeout=cache_timeout) 
    File "C:\Python27\lib\site-packages\flask-0.10.1-py2.7.egg\flask\helpers.py", line 612, in send_from_directory 
    filename = safe_join(directory, filename) 
    File "C:\Python27\lib\site-packages\flask-0.10.1-py2.7.egg\flask\helpers.py", line 582, in safe_join 
    return os.path.join(directory, filename) 
    File "C:\Python27\lib\ntpath.py", line 85, in join 
    result_path = result_path + p_path 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 8: ordinal not in range(128) 

回答

3

由於Python的回溯告訴你,有一個UnicodeDecodeError

我期望它來自您致電render_template燒瓶功能。
render_template函數使用期望Unicode字符串的Jinja。

默認情況下,Python 2.x中的字符串是一個字節字符串。
把它改成統一使用:

>>> byte_string = 'I have a non-ASCII character: €' 
>>> type(byte_string) 
<type 'str'> 
>>> unicode_string = byte_string.decode('utf-8') 
>>> type(unicode_string) 
<type 'unicode'> 

具體你可以做的是:

  • 使用

    轉換傳遞給render_template爲Unicode
  • 默認啓用Unicode字符串串

    import sys 
    reload(sys) 
    sys.setdefaultencoding("utf-8") 
    

    這不是最安全的選擇H(見here

如果它是一個新的項目,你可以使用Python 3,直接在默認情況下使用Unicode。