如何阻止拉丁1字符的Unicode表示?

2024-09-28 22:20:18 发布

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

如何防止Flask返回拉丁字符作为Unicode表示?例如,对于这类字符:http://graphemica.com/%C3%91

我的FlaskApp在MySQL数据库中执行SELECT,逐行检索,将它们添加到列表中,将列表存储到字典中,最后返回一个JSON。在

烧瓶

@app.route("/json")
def show_json():
    avisos_dict = {}
    records_list = []
    query = "SELECT * FROM tjs_stage.avisos"
    cur.execute(query)
    con.commit()
    records = cur.fetchall()
    for row in records:
        records_list.append(row)
    avisos_dict['avisos'] = records_list
    return jsonify(avisos_dict)

MySQL数据

^{pr2}$

JSON

enter image description here

有人知道怎么解决这个问题吗?在

提前感谢;)


Tags: jsonflask列表mysqlunicodequery字符select
1条回答
网友
1楼 · 发布于 2024-09-28 22:20:18

"Ñ""\u00d1"json字符串表示相同的U+00D1Unicode字符:

>>> import json
>>> json.loads(u'"Ñ"') == json.loads(u'"\\u00d1"')
True

注意:反斜杠是转义的,因为它在Python字符串文本中也是特殊的。在

要避免ascii编码的json,set ^{} to ^{}

By default Flask serialize object to ascii-encoded JSON. If this is set to False Flask will not encode to ASCII and output strings as-is and return unicode strings. jsonify will automatically encode it in utf-8 then for transport for instance.

示例:

^{pr2}$

要运行服务器(假设您将其保存到app.py),请执行以下操作:

$ python -mpip install flask -U
$ python app.py

要测试它:

$ python -mpip install httpie
$ http  pretty=none :5000

输出:

HTTP/1.0 200 OK
Content-Length: 18
Content-Type: application/json
Date: Tue, 31 May 2016 14:54:20 GMT
Server: Werkzeug/0.10.4 Python/2.7.9

{
    "text": "Ñ"
}

@Hareendra Chamara Philips在the comment中建议:

Alternatively, if some one is using config.py and doing application.config.from_pyfile('config.py') in __init__.py, you can use JSON_AS_ASCII = False in the config.py.

相关问题 更多 >