【问题标题】:How to correctly produce and consume UTF-8 json in Python3? (with flask and requests)如何在 Python3 中正确生成和使用 UTF-8 json? (带烧瓶和请求)
【发布时间】:2017-10-17 16:12:10
【问题描述】:

我编写了一些基本代码来解释我的问题:

produceUTF8.py(使用 unicode 字符回复“ít wórked!”)- 你先运行这个

# -*- coding: utf-8 -*-
import os
from sys import argv

from flask import Flask, request, Response, jsonify
import json

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False # contribution from Erdem

@app.route('/reply', methods=['POST'])
def reply():
    """Fetch a reply
    """
    print("DEBUG entered")
    params = request.json
    print("DEBUG entered2")
    if not params:
        return jsonify({
            'status': 'error',
            'error': 'Request must be of the application/json type!',
        })

    reply = "ít wórked!"

    # Send the response.
    return jsonify({
        'status': 'ok',
        'reply': reply,
    })

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

consumeUTF8.py(发布消息“óíá”以获得生产者的答复)

# -*- coding: utf-8 -*-
import requests

HEADERS = {'Content-Type': 'application/json; charset=utf-8',}
DATA = '{"message": "óíá"}'
my_request = requests.post('http://localhost:5000/reply', headers=HEADERS, data=DATA)
response = my_request.json()['reply']

在我的生产者中,我收到“错误请求 (400)”,在消费者中收到“json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)”。

从调试打印中可以看出,params = request.json 中似乎存在问题。这里推荐的方法是什么?

谢谢!

【问题讨论】:

    标签: json python-3.x flask utf-8


    【解决方案1】:

    您可以通过编码data 对象来修复发出请求的方式:

    my_request = requests.post('http://localhost:5000/reply', 
                               headers=HEADERS, 
                               data=DATA.encode('utf-8'))
    
    #>>> ít wórked with óíá!
    

    如果您在应用程序中添加 try/except 语句,它会返回:

    try:
        params = request.json
    except Exception as e:
        params = None
        print(e)
    

    400 错误请求:无法解码 JSON 对象:“utf-8”编解码器无法解码位置 14 中的字节 0xf3:无效的继续字节

    您可以使用此模式为 param 分配默认值

    【讨论】:

    • 它停止了错误请求!谢谢.. 我将在 Postman sn-p 生成器上创建一个问题以添加此编码部分 =)
    【解决方案2】:

    我没有尝试过代码,但可能正在设置

    app.config['JSON_AS_ASCII'] = False
    

    可能有帮助。

    【讨论】:

    • 现在它可以在 Postman 上使用 UTF-8 的响应,但它仍然收到来自 consumeUTF8.py 的错误请求 (400)。我用您的贡献编辑了代码,谢谢!更疯狂的是,我使用 request 和 http.client 从 Postman 生成了 sn-ps,他们也得到了同样的错误!
    猜你喜欢
    • 2014-07-23
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 2012-04-25
    • 2021-12-30
    • 1970-01-01
    相关资源
    最近更新 更多