Flask、SQLAlchemy和Jinja2 - UnicodeDecodeError

6
我有一个使用Flask、SQLAlchemy和WTForms的Web应用程序,以及必要的Flask扩展程序使其正常工作。MySQL对于所有表和列都使用utf8_bin。
我插入了一些中文字符,phpMyAdmin正确显示它们,但每当我尝试打开页面时,就会出现以下异常:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)
我知道我应该对要显示的字段进行decode('utf8'),但这不应该由SQLAlchemy自动处理吗?
我唯一成功的方法是遍历结果列表并执行类似以下的操作:
object.property = object.property.decode('utf8')
但显然,这不应该手动完成。我错过了什么?
更新:SQLAlchemy映射
class Thread(db.Model):

    __tablename__ = 'Thread'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.Unicode(255), nullable=False)
    body = db.Column(db.Text, nullable=True)
    date_created = db.Column(db.DateTime, nullable=False, default=datetime.now())
    created_by = db.Column(db.Integer, ForeignKey(User.id))
    user = relationship(User, backref='threads')
    display_hash = db.Column(db.Unicode(255), nullable=False, unique=True)
    display_name = db.Column(db.Unicode(255), nullable=True)
    nsfw = db.Column(db.Boolean, nullable=False, default=False)
    last_updated = db.Column(db.DateTime, nullable=False)

    def __init__(self, title=None, body=None, category_id=None, display_name=None):
        self.title = title
        self.body = body
        self.category_id = category_id
        self.display_name = display_name
        self.display_hash = custom_uuid()
        self.last_updated = self.date_created

    def __repr__(self):
        return u'<Thread %r>' % (self.title)

    def url_title(self):
        """ Generates an ASCII-only slug. """

        result = []
        for word in _punct_re.split(self.title.lower()):
            result.extend(unidecode(word).split())
        return unicode(u'-'.join(result))

更新:堆栈跟踪

`127.0.0.1 - - [06/Oct/2013 02:37:15] "GET /index HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/Users/homedirectory/.virtualenvs/fruitshow/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/homedirectory/.virtualenvs/fruitshow/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/Users/homedirectory/.virtualenvs/fruitshow/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/homedirectory/.virtualenvs/fruitshow/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/homedirectory/.virtualenvs/fruitshow/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/homedirectory/.virtualenvs/fruitshow/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/homedirectory/.virtualenvs/fruitshow/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/homedirectory/.virtualenvs/fruitshow/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/homedirectory/Projects/Assorted/Fruit Show/app/views.py", line 90, in index
    return render_template('index.html', threads=threads, pagination=pagination)
  File "/Users/homedirectory/.virtualenvs/fruitshow/lib/python2.7/site-packages/flask/templating.py", line 128, in render_template
    context, ctx.app)
  File "/Users/homedirectory/.virtualenvs/fruitshow/lib/python2.7/site-packages/flask/templating.py", line 110, in _render
    rv = template.render(context)
  File "/Users/homedirectory/.virtualenvs/fruitshow/lib/python2.7/site-packages/jinja2/environment.py", line 969, in render
    return self.environment.handle_exception(exc_info, True)
  File "/Users/homedirectory/.virtualenvs/fruitshow/lib/python2.7/site-packages/jinja2/environment.py", line 742, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/homedirectory/Projects/Assorted/Fruit Show/app/templates/index.html", line 1, in top-level template code
    {% extends 'base.html' %}
  File "/Users/homedirectory/Projects/Assorted/Fruit Show/app/templates/base.html", line 50, in top-level template code
    {% block content %}
  File "/Users/homedirectory/Projects/Assorted/Fruit Show/app/templates/index.html", line 14, in block "content"
    <a href="{{ url_for('new_thread') }}/{{ thread.display_hash|safe }}/{{ thread.url_title()|safe }}">{{ thread.title|safe }}</a>
  File "/Users/homedirectory/.virtualenvs/fruitshow/lib/python2.7/site-packages/jinja2/filters.py", line 747, in do_mark_safe
    return Markup(value)
  File "/Users/homedirectory/.virtualenvs/fruitshow/lib/python2.7/site-packages/markupsafe/__init__.py", line 72, in __new__
    return text_type.__new__(cls, base)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)`

更新:项目存储库的 URL:

https://github.com/ruipacheco/fruitshow


请在您的问题中更新涉及到的SQLAlchemy模型,以便我们更好地帮助您解决问题。 - Mark Hildreth
谢谢您的更新。您能否同时更新您的问题并提供一个简短的代码片段,以便复制错误,包括代码提供的完整堆栈跟踪。 - Mark Hildreth
此外,MySQL可能会将客户端连接默认为使用latin1,即使表和列正在使用unicode。 - Mark Hildreth
不确定是否能够添加任何代码,因为没有,这都是框架。我将数据放入数据库中。phpMyAdmin显示正确的字符。我获取数据,不进行修改,但Jinja2出现错误。连接字符串已经包含了 ?charset=utf8 以告知数据库我们想要使用utf8。 - ruipacheco
给答案添加了堆栈跟踪。将use_unicode=1添加到连接字符串中并没有起作用。 - ruipacheco
SQLAlchemy 返回的标题列是 Unicode 还是 str? - ajknzhol
4个回答

4
问题出在我使用的MySQL驱动程序上。
我按照这个答案所说的做法,将列类型从utf8_bin切换到utf8_general_ci就解决了问题。

2

关于您的模型中的Slug字段,我有一个小建议。

有一个名为Webhelpershttps://pypi.python.org/pypi/WebHelpers)的库,导入它后,您的标题将自动转换为slug。

安装WebHelpers,然后导入urlify

from webhelpers.text import urlify
.
.
.
@property
def slug(self):
    return urlify(self.title)

0

虽然不完全是你想要的答案,但我想推荐ftfy(Fix Text For You),它可以修复许多小的Unicode和HTML转义问题。在Unicode编码中,有一个非常令人烦恼的宗教战争,那就是UTF-8无法处理各种单字节字符编码,例如Latin-1。解码器不会只是简单地认为“哦,这一定是一个简单的拉丁字符”,而是会变得慌乱。当你的数据库驱动程序观察到“哦,这个符合条件”,它就会创建一个法特瓦。


0

在连接参数中设置字符集只是告诉MySQL将列从数据库中的格式转换为请求的编码格式。数据仍然以字节形式在MySQL和客户端之间传递。简而言之,您必须告诉sqlalchemy这个特定的数据是Unicode数据(在连接的编码中)。对于大多数列,您已经使用了Unicode,它可以实现此目的。一个值得注意的例外是body,它的类型是Text。您可能想要使用UnicodeTextText(convert_unicode=True)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接