如何在 Python3 中正确生成和使用 UTF-8 json?(带烧瓶和请求) [英] How to correctly produce and consume UTF-8 json in Python3? (with flask and requests)

查看:133
本文介绍了如何在 Python3 中正确生成和使用 UTF-8 json?(带烧瓶和请求)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

# -*- 编码:utf-8 -*-导入操作系统从 sys 导入 argv从烧瓶导入烧瓶,请求,响应,jsonify导入jsonapp = Flask(__name__)app.config['JSON_AS_ASCII'] = False # 来自 Erdem 的贡献@app.route('/reply', methods=['POST'])定义回复():"""获取回复"""打印(进入调试")参数 = request.json打印(调试进入2")如果不是参数:返回 jsonify({'状态':'错误','error': '请求必须是 application/json 类型!',})回复 = "没有成功!"# 发送响应.返回 jsonify({'状态':'好的','回复':回复,})如果 __name__ == '__main__':app.run(host='0.0.0.0', debug=True)

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

# -*- 编码:utf-8 -*-进口请求HEADERS = {'内容类型':'应用程序/json;字符集=utf-8',}数据 = '{"message": "óíá"}'my_request = requests.post('http://localhost:5000/reply', headers=HEADERS, data=DATA)response = my_request.json()['reply']

在我的生产者中,我收到Bad Request (400)"和在消费者中json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)".

在调试打印中看到的 params = request.json 似乎有问题.这里推荐的方法是什么?

谢谢!

解决方案

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

my_request = requests.post('http://localhost:5000/reply',标题=标题,数据=DATA.encode('utf-8'))#>>>ít 与óíá 一起工作!

<小时>

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

尝试:参数 = request.json除了作为 e 的例外:参数 = 无打印(e)

<块引用>

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

您可以使用此模式为 param

分配默认值

I've made some basic code to explain my question:

produceUTF8.py (replies 'ít wórked!' with unicode characters) - you run this first

# -*- 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 (posts the message 'óíá' to get answer from producer)

# -*- 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']

In my producer I am getting "Bad Request (400)" and in the consumer "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)."

It seems to be a problem in params = request.json as seen in the debug prints. What is the recommended approach here?

Thanks!

解决方案

You can fix the way you make the request by encoding the data object :

my_request = requests.post('http://localhost:5000/reply', 
                           headers=HEADERS, 
                           data=DATA.encode('utf-8'))

#>>> ít wórked with óíá!


If you add a try/except statement in the app, it returns :

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

400 Bad Request: Failed to decode JSON object: 'utf-8' codec can't decode byte 0xf3 in position 14: invalid continuation byte

You could use this pattern to assign a default value for param

这篇关于如何在 Python3 中正确生成和使用 UTF-8 json?(带烧瓶和请求)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆