![](/img/trans.png)
[英]Flask code raises UnicodeDecodeError (only) when ran from outside Eclipse
[英]Sending static file with Flask raises UnicodeDecodeError
我正在嘗試鏈接到Flask中的靜態CSS文件。 但是,靜態路由會引發UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 8: ordinal not in range(128)
嘗試發送文件時, UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 8: ordinal not in range(128)
。 為什么會出現此錯誤,我該如何解決?
<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)
正如Python追溯告訴您的那樣,存在一個UnicodeDecodeError
。
我希望它來自您對render_template
Flask函數的render_template
。
render_template
函數使用Jinja,它需要Unicode字符串。
默認情況下,Python 2.x中的字符串是字節字符串。
要將其更改為Unicode,請使用:
>>> 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")
不過,這不是最安全的選擇(請參閱此處 )
如果是用於新項目,則可以直接使用Python 3,默認情況下使用Unicode。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.