首页 > 解决方案 > Flask request.get_data() 不处理 UTF-8 字符

问题描述

我已经用 Python 编写了一个简单的 Flask Web 服务,它需要带有字符串作为数据的 HTTP POST 请求。

@app.route('/hello', methods=['POST'])
def hello():

json_response = {}
data = request.get_data(as_text=True)

json_response['data'] = data
return json_response

当我尝试使用 cURL 使用 ASCII 字符串调用它时,它工作正常:

curl 127.0.0.1:5000/hello -X POST -H "Content-Type: text/plain" -d "hello world"
{
  "data": "hello world"
}

但是,当我尝试使用包含 UTF-8 字符的字符串调用它时,无法正确读取 UTF-8 字符,而是替换为替换字符(就像decode('utf-8', 'replace')会一样):

curl 127.0.0.1:5000/hello -X POST -H "Content-Type: text/plain" -d "hello €"
{
  "data": "hello \ufffd"
}

我认为重点get_data(as_text=True)是将数据作为 Unicode 字符串读取?我在这里错过了什么吗?

标签: pythonflaskcurl

解决方案



推荐阅读