Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 烧瓶、SQLAlchemy和Jinja2-UnicodeDecodeError_Python_Sqlalchemy_Flask_Jinja2_Flask Sqlalchemy - Fatal编程技术网

Python 烧瓶、SQLAlchemy和Jinja2-UnicodeDecodeError

Python 烧瓶、SQLAlchemy和Jinja2-UnicodeDecodeError,python,sqlalchemy,flask,jinja2,flask-sqlalchemy,Python,Sqlalchemy,Flask,Jinja2,Flask Sqlalchemy,我有一个web应用程序,它使用Flask、SQLAlchemy和WTForms,以及必要的Flask扩展来实现所有功能。MySQL正在对所有表和列使用utf8\u bin 我插入了一些中文字符,phpMyAdmin正确显示它们,但每当我尝试打开页面时,都会出现以下异常: UnicodeDecodeError:“ascii”编解码器无法解码位置0:序号不在范围(128)中的字节0xe6 我知道我应该解码('utf8')我想显示的字段,但这不应该由SQLAlchemy为我处理吗 我成功完成这项工作的

我有一个web应用程序,它使用Flask、SQLAlchemy和WTForms,以及必要的Flask扩展来实现所有功能。MySQL正在对所有表和列使用
utf8\u bin

我插入了一些中文字符,phpMyAdmin正确显示它们,但每当我尝试打开页面时,都会出现以下异常:

UnicodeDecodeError:“ascii”编解码器无法解码位置0:序号不在范围(128)中的字节0xe6

我知道我应该
解码('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))
类线程(db.Model):
__tablename_uu='Thread'
id=db.Column(db.Integer,主键=True)
title=db.Column(db.Unicode(255),null=False)
body=db.Column(db.Text,nullable=True)
date\u created=db.Column(db.DateTime,nullable=False,default=DateTime.now())
创建人=db.Column(db.Integer,ForeignKey(User.id))
用户=关系(用户,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)
定义初始化(self,title=None,body=None,category\u id=None,display\u name=None):
self.title=标题
self.body=身体
self.category\u id=category\u id
self.display\u name=display\u name
self.display\u hash=custom\u uuid()
self.last\u updated=self.date\u创建
定义报告(自我):
返回u“”%(self.title)
def url_标题(自我):
“”“生成仅ASCII的段塞。”“”
结果=[]
对于“点拆分”(self.title.lower())中的单词:
extend(unidecode(word).split())
返回unicode(u'-'.连接(结果))
更新:堆栈跟踪

`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)`
`127.0.0.1---[06/Oct/2013 02:37:15]“GET/index HTTP/1.1”500-
回溯(最近一次呼叫最后一次):
文件“/Users/homeditory/.virtualenvs/fruitshow/lib/python2.7/site packages/flask/app.py”,第1836行,在调用中__
返回self.wsgi_应用程序(环境,启动响应)
wsgi_应用程序中的文件“/Users/homeditory/.virtualenvs/fruitshow/lib/python2.7/site packages/flask/app.py”,第1820行
响应=self.make\u响应(self.handle\u异常(e))
文件“/Users/homeditory/.virtualenvs/fruitshow/lib/python2.7/site packages/flask/app.py”,第1403行,在句柄中
重放(exc_类型、exc_值、tb)
wsgi_应用程序中的文件“/Users/homeditory/.virtualenvs/fruitshow/lib/python2.7/site packages/flask/app.py”,第1817行
response=self.full\u dispatch\u request()
文件“/Users/homeditory/.virtualenvs/fruitshow/lib/python2.7/site packages/flask/app.py”,第1477行,完整发送请求
rv=自身处理用户异常(e)
文件“/Users/homedirectory/.virtualenvs/fruitshow/lib/python2.7/site packages/flask/app.py”,第1381行,在handle\u user\u异常中
重放(exc_类型、exc_值、tb)
文件“/Users/homeditory/.virtualenvs/fruitshow/lib/python2.7/site packages/flask/app.py”,第1475行,完整发送请求
rv=自我分派请求()
文件“/Users/homeditory/.virtualenvs/fruitshow/lib/python2.7/site packages/flask/app.py”,第1461行,在调度请求中
返回self.view_函数[rule.endpoint](**req.view_参数)
文件“/Users/homeditory/Projects/schodled/Fruit Show/app/views.py”,第90行,索引中
返回render_模板('index.html',threads=threads,pagination=pagination)
文件“/Users/homeditory/.virtualenvs/fruitshow/lib/python2.7/site packages/flask/templating.py”,第128行,在render_模板中
上下文(ctx.app)
文件“/Users/homeditory/.virtualenvs/fruitshow/lib/python2.7/site packages/flask/templating.py”,第110行,在_render中
rv=template.render(上下文)
文件“/Users/homeditory/.virtualenvs/fruitshow/lib/python2.7/site packages/jinja2/environment.py”,第969行,在渲染中
返回self.environment.handle\u异常(exc\u info,True)
文件“/Users/homedirectory/.virtualenvs/fruitshow/lib/python2.7/site packages/jinja2/environment.py”,第742行,在句柄中
重放(exc_类型、exc_值、tb)
顶级模板代码中的文件“/Users/homeditory/Projects/schodled/Fruit Show/app/templates/index.html”,第1行
{%extends'base.html%}
文件“/Users/homeditory/Projects/schodled/Fruit Show/app/templates/base.html”,第50行,顶级模板代码
{%block content%}
文件“/Users/homeditory/Projects/schodled/Fruit Show/app/templates/index.html”,第14行,在“内容”块中
文件“/Users/homeditory/.virtualenvs/fruitshow/lib/python2.7/site-packages/jinja2/filters.py”,第747行,在do_-mark_-safe中
返回标记(值)
文件“/Users/homeditory/.virtualenvs/fruitshow/lib/python2.7/site packages/markupsafe/\uuuu init\uuuuuuuuuuuuuuu.py”,第72行,新__
返回文本类型。新建(cls,基本)
UnicodeDecodeError:“ascii”编解码器无法解码位置0中的字节0xe6:序号不在范围内(128)`
更新:项目回购的URL:


在连接参数中设置字符集只会告诉mysql将数据库中的列转换为请求的编码格式。数据仍然以字节的形式在MySQL和客户端之间传递。简而言之,您必须告诉
sqlalchemy
“此特定”数据是unicode数据(在连接的编码中)。对于您的大多数列,您都使用了
Unicode
,这就满足了这一目的。一个显著的突出点是
主体
,它是一种类型。
from webhelpers.text import urlify
.
.
.
@property
def slug(self):
    return urlify(self.title)