我正在尝试使用flask-admin为我的应用程序构建一个后端界面。 当我尝试访问表单以创建新条目时,我得到:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 13: ordinal not in range(128)
通过堆栈跟踪,问题是我表中的某些项包含非ascii字符。我该如何解决这个问题? 谢谢!
答案 0 :(得分:1)
你应该使用unicode字符串,就像这样
u"whaterver string"
答案 1 :(得分:1)
一些旧代码也有同样的问题。只要您:
str
(而不是unicode
)对象表示非ASCII数据,并且ascii
(通常是这样)。第二个问题可能源于您持有的String
所在的SQLAlchemy Unicode
列,或者当您应该编写“u'šömething”时编写了'šömething'
-这可能是由于通常很难找出问题的实际根源。
但是,通过方程式的hacking the third component(尽管通常为not recommended)很容易解决。将这些行添加到代码中的某处应该可以解决问题(将实际问题隐藏在地毯下):
import sys
reload(sys)
sys.setdefaultencoding('UTF8')
答案 2 :(得分:0)
通常,通过使用unicode.encode()
方法强制字符串数组为unicode来解决此错误。
来自主题的Python Wiki页面
>>> u"a".encode("utf-8")
'a'
>>> u"\u0411".encode("utf-8")
'\xd0\x91'
>>> "a".encode("utf-8") # Unexpected argument type.
'a'
>>> "\xd0\x91".encode("utf-8") # Unexpected argument type.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)
我认为最好通过修改负责字段格式化的jinja宏来强制将值转换为unicode。