如何在Python3中正确产生和使用UTF-8 json?(带烧瓶和要求)

静态开发

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

producerUTF8.py(用Unicode字符回复“'t wrked!”)-您首先运行此代码

# -*- 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)

消耗UTF8.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:期望值:第1行第1列(字符0)”。

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

谢谢!

PRMoureu

您可以通过编码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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在python中正确使用'or'和'and'

如何使用Python 3在MySQL中避免使用b'和UTF-8文字

使用带有curses边框和python3的utf-8编码

无法在JSON中正确声明和显示UTF-8字符

python 3中的字节流和utf-8

如何在 Python 中结合 .decode('utf-8') 和 .format() ?

如何在 python 中以 UTF-8 样式编写和编码我的文件?

如何使用node.js,mssql和msnodesqlv8在事务中正确执行循环查询

python和json UTF-8编码

如何在Angular 8中正确使用PrimeNg Toast

如何在Angular 8中正确使用setValue

如何使用Python从mysql数据库中获取和打印utf-8数据?

如何在python中正确地将长文本正确编码为utf-8?

Windows Phone 8和带键盘的接头

如何保存utf-8 JSON值并将其正确写入Python 3.8.2中的utf-8 txt文件?

如何在python中正确使用json

如何在Python3中将UTF-8 CSV写入BytesIO中?

如何使用jdbc和MySQL正确设置utf8编码?

如何使用 QSettings 将 UTF-8 字符正确写入 *.ini 文件的 [section] 和 [name]?

如何在Python3中修复或删除格式错误的utf-8字符

带create_app,SQLAlchemy和Celery的烧瓶

使用python 3和请求时,来自网站的UTF-8文本无法正确解码,与Python 2配合使用并机械化

utf-8的python 2和python 3之间的区别

如何在Java中的ISO-8859-1和UTF-8之间转换?

如何在Symfony XmlEncoder中设置编码UTF-8和xmlns属性

如何在以 utf-8 格式保存的文件的单行中读取和比较不同的单词?在蟒蛇?

在Python 3.5中编码utf-8和utf8之间的区别

utf-8和json_encode中的PHP编码

如何在Sublime Text 3中正确格式化/缩进HTML和PHP代码