V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
barbery
V2EX  ›  Python

请问大家 在Flask中,是怎么传递list 到 jinja2 模板中输出的?我一输出就报错:UnicodeDecodeError

  •  
  •   barbery ·
    barbery · 2012-12-28 21:29:54 +08:00 · 5058 次点击
    这是一个创建于 4131 天前的主题,其中的信息可能已经有所发展或是发生改变。
    完整报错信息:“UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)”

    我知道unicode(str, 'utf-8')后再传递过去就没事。。。但是从mysql中取到的结果是tuple,该不会是每次从mysql取到结果集 都要迭代一次转码吧???
    我现在的做法是 获得结果集后 result= [unicode(row[1], 'utf-8') for row in data] 这样迭代一次转码后才能传递过去模板那里输出。。。我对此做法相当不满。。。求指教!!!
    5 条回复    1970-01-01 08:00:00 +08:00
    BeanYoung
        1
    BeanYoung  
       2012-12-28 23:08:13 +08:00   ❤️ 2
    import sys
    reload(sys)
    sys.setdefaultencoding('utf-8')
    barbery
        2
    barbery  
    OP
       2012-12-28 23:49:28 +08:00
    @BeanYoung 感谢啊。。。加了sys.setdefaultencoding('utf-8') 就可以了。。。请问一下是什么原理?为什么我加了 #coding=utf-8 不行,要sys.setdefaultencoding('utf-8')才行?
    davidx
        3
    davidx  
       2012-12-29 00:40:36 +08:00
    我感觉你从mysql过来的数据, 就不是unicode或者utf-8吧
    linuxsand
        4
    linuxsand  
       2012-12-29 00:45:22 +08:00
    @barbery #coding=utf-8 是指定该 .py 文件编码,若其中出现非 ascii 字符 python 会知道如何处理。

    而后者,请用 help()
    barbery
        5
    barbery  
    OP
       2012-12-29 12:50:09 +08:00
    谢谢大家。。。结贴!!!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2354 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 16:09 · PVG 00:09 · LAX 09:09 · JFK 12:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.