我编写了一些基本代码来解释我的问题:
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
从调试打印中可以看出,这似乎是一个问题。这里推荐的方法是什么?
谢谢!
您可以通过编码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] 删除。
我来说两句