【发布时间】: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