当前位置:首页 » python web » 正文

解决flask接口返回的内容中文乱码的问题

看: 1150次  时间:2020-07-24  分类 : python web

写一个简单的例子程序:

# coding:utf-8
import flask
from flask import json, jsonify, request, render_template

app = flask.Flask(__name__)

@app.route("/api", methods=["GET", "POST"])
def api():
 if request.method == 'GET':
  return jsonify({"login status": "成功1"})
 elif request.method == "POST":
  data = request.get_data()
  data = json.loads(data)
  if data["name"] == "dom":
   return jsonify({"login": "成功2"})
  else:
   return jsonify({"login": "fail"})

if __name__ == "__main__":
 app.run(host='127.0.0.1', port='8080')

运行后访问网页,内容中的中文显示乱码

解决方式:

给app配置app.config[‘JSON_AS_ASCII'] = False,即:

if __name__ == "__main__":
 app.run(host='127.0.0.1', port='8080')

变为:

if __name__ == "__main__":
 app.config['JSON_AS_ASCII'] = False
 app.run(host='127.0.0.1', port='8080')

补充知识:Flask中 request.files.get('file') 后的文件对象在读取时(中文)乱码

一、问题引出

我们通常需要接收前端发送过来的文件,而在Flask中通常采取file_obj = request.files.get(‘file') 的方式获取文件对象,按照Flask官方文档的介绍,返回值 file_obj 是一个文件对象,但是我们平常在使用时通常是在open() 函数中指定打开方式的,可是这里并不知道这个文件对象中的数据是何种编码方式,因此就会出现中文乱码的问题。如下所示:当上传的文件内容中包含中文时就会出现乱码:

file_obj = request.files.get('file')
file_content = file_obj.read()
print('答案内容为:', file_content)

二、解决过程探索

通过Flask的官方文档及源码得知:

request.files 包含了所有上传文件的MultiDict对象。文件中的每个键都是来自 "的名称。文件中的每个值都是一个Werkzeug FileStorage对象。参考:Flask API

而类 FileStorage 是被这样描述的:FileStorage类是传入文件的一个简单包装。请求对象使用它来表示上传的文件。并且 FileStorage 提供了一些方法,最长用的就是如下几个:参考:Werkzeug DataStructures

filename   The filename of the file on the client.
name   The name of the form field.
save   (dst, buffer_size=16384)Save the file to a destination path or file object. If the destination is a file object you have to close it yourself after the call. The buffer size is the number of bytes held in memory during the copy process. It defaults to 16KB. 等等

但是并没有找到Flask在得到这个文件对象时的编码方式。

三、解决办法

先从文件对象中将内容读出,然后再按照我们想要的格式解码(通常 utf-8)。

file_obj = request.files.get('file')
file_content = file_obj.read()
file_content = file_content.decode("utf-8")
print('答案内容为:', file_content)

这样文件中的中文内容就不会乱码了。

以上这篇解决flask接口返回的内容中文乱码的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

标签:flask  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!