亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

寫一個(gè)簡(jiǎn)單的例子程序:

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

運(yùn)行后訪問(wèn)網(wǎng)頁(yè),內(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')

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

一、問(wèn)題引出

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

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

二、解決過(guò)程探索

通過(guò)Flask的官方文檔及源碼得知:

request.files 包含了所有上傳文件的MultiDict對(duì)象。文件中的每個(gè)鍵都是來(lái)自 "的名稱。文件中的每個(gè)值都是一個(gè)Werkzeug FileStorage對(duì)象。參考:Flask API

而類 FileStorage 是被這樣描述的:FileStorage類是傳入文件的一個(gè)簡(jiǎn)單包裝。請(qǐng)求對(duì)象使用它來(lái)表示上傳的文件。并且 FileStorage 提供了一些方法,最長(zhǎng)用的就是如下幾個(gè):參考: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. 等等

但是并沒(méi)有找到Flask在得到這個(gè)文件對(duì)象時(shí)的編碼方式。

三、解決辦法

先從文件對(duì)象中將內(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)容就不會(huì)亂碼了。

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

相關(guān)文章

最新評(píng)論