PostgreSQL、Python、Jinja2编码

2024-10-01 17:34:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我的应用程序编码有问题,在web上找不到解决方案。在

以下是场景:

  • 使用UTF-8编码的PostgreSQL(CREATE DATABASE xxxx WITH ENCODING 'UTF8'

  • Python逻辑也使用UTF-8编码(# -*- coding: utf-8 -*-

  • Jinja2显示我的HTML页面。Python和Jinja2用于Flask,这是我使用的微框架。

我的页眉有:<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

好吧,使用psycopg2执行一个简单的查询并将其打印到Jinja2上,我得到的结果是:

{% for company in list %}
    <li>
        {{ company }}
    </li>
{% endfor %}

(1,'Casa das M\xc3\xa1quinas','R.Tr\xc3\xaas,Mineiros-Goi\xc3\xa1s')

(2,“Ar do Z\xc3\xa9”,“Av。S\xc3\xa9tima,Mineiros-Goi\xc3\xa1s')

如果我试着深入田野:

^{pr2}$

我得到以下错误:UnicodeDecodeError:'ascii'编解码器无法解码第10位的字节0xc3:序号不在范围内(128)

但是,如果在将列表字段发送到Jinja2之前打印这些字段,我会得到预期的结果(postgresql中也是这样表示的):

1 马奎纳斯之家 R、 特里斯,米尼罗斯-戈亚斯

二 阿多·泽 Av。塞蒂玛,米尼罗斯-戈亚斯

当我得到错误时,Flask提供了一个“调试”选项。这就是代码中断的地方 File“/home/anonimou/Desktop/flask/lib/python2.7/site-packages/jinja2//u markupsafe/_原生.py“,第21行,在逃跑 返回标记(unicode)

我也可以:

[console ready]

>>> print s
Casa das Máquinas

>>> s
'Casa das M\xc3\xa1quinas'

>>> unicode(s)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 10: ordinal not in range(128)

>>> s.decode('utf-8')
u'Casa das M\xe1quinas'

>>> s.encode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 10: ordinal not in range(128)

>>> s.decode('utf-8').encode('utf-8')
'Casa das M\xc3\xa1quinas'

>>> print s.decode('utf-8').encode('utf-8')
Casa das Máquinas

>>> print s.decode('utf-8')
Casa das Máquinas

我已经试着解码了,我已经试着解码了。同样的错误。在

所以,我不知道我能做什么。=(

提前谢谢!在


Tags: injinja2编码错误ascii解码utfprint
1条回答
网友
1楼 · 发布于 2024-10-01 17:34:29

问题是psycopg2 returns byte strings by default in Python 2

When reading data from the database, in Python 2 the strings returned are usually 8 bit str objects encoded in the database client encoding

所以你可以:

  • 手动将所有数据解码为UTF-8:

    # Decode the byte strings into Unicode objects using
    # the encoding you know that your database is using.
    companies = [company.decode("utf-8") for company in companies]
    return render_template("companies.html", companies=companies)
    

  • 第一次导入psycopg2时,请按照手册同一节中的说明设置编码器:

    Note In Python 2, if you want to uniformly receive all your database input in Unicode, you can register the related typecasters globally as soon as Psycopg is imported:

    ^{pr2}$

    and then forget about this story.

相关问题 更多 >

    热门问题