欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

解決flask接口返回的內(nèi)容中文亂碼的問題

 更新時間:2020年04月03日 10:04:12   作者:dushu990  
這篇文章主要介紹了解決flask接口返回的內(nèi)容中文亂碼的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

寫一個簡單的例子程序:

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

運行后訪問網(wǎng)頁,內(nèi)容中的中文顯示亂碼

解決方式:

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

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

變?yōu)椋?/p>

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

補充知識:Flask中 request.files.get('file') 后的文件對象在讀取時(中文)亂碼

一、問題引出

我們通常需要接收前端發(fā)送過來的文件,而在Flask中通常采取file_obj = request.files.get(‘file') 的方式獲取文件對象,按照Flask官方文檔的介紹,返回值 file_obj 是一個文件對象,但是我們平常在使用時通常是在open() 函數(shù)中指定打開方式的,可是這里并不知道這個文件對象中的數(shù)據(jù)是何種編碼方式,因此就會出現(xiàn)中文亂碼的問題。如下所示:當上傳的文件內(nèi)容中包含中文時就會出現(xiàn)亂碼:

file_obj = request.files.get('file')
file_content = file_obj.read()
print('答案內(nèi)容為:', 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在得到這個文件對象時的編碼方式。

三、解決辦法

先從文件對象中將內(nèi)容讀出,然后再按照我們想要的格式解碼(通常 utf-8)。

file_obj = request.files.get('file')
file_content = file_obj.read()
file_content = file_content.decode("utf-8")
print('答案內(nèi)容為:', file_content)

這樣文件中的中文內(nèi)容就不會亂碼了。

以上這篇解決flask接口返回的內(nèi)容中文亂碼的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論