簡體   English   中英

來自flask的響應在React前端收到的Json上有額外的鍵

[英]Response from flask has extra key on Json received by React front

所以,我有一個或多或少像這樣工作的端點:

from flask import Flask, request, jsonify
from flask_cors import CORS

import json
from werkzeug.utils import secure_filename
import os


from mylib import do_stuff

path = os.getcwd()
UPLOAD_FOLDER = os.path.join(path, 'data')
# #load flask
app = Flask(__name__)
CORS(app)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['JSON_AS_ASCII'] = False



print(UPLOAD_FOLDER,flush=True)
@app.route('/upload', methods=['POST'])
def upload():
    if request.method == 'POST':
        file = request.files['file']
        if file:
            try:
                # Receives a file and saves on the server
                filename = secure_filename(file.filename)
                file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                print("saving_here {}".format(file_path))
                file.save(file_path)

                # The result here is a dict of dicts of dicts
                # It consists of a dictionary of DataFrames().to_dict()
                result = do_stuff(file_path)


                response = app.response_class(
                    response=json.dumps(result ),
                    status=200,
                    mimetype='application/json'
                )
                return response

            except Exception as e:
                print(e,flush=True)
                return "error"

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port= <PORT>)

這里的主要問題是,在前端有時我會收到一個帶有“消息”鍵的答案,有時我會收到一個沒有它的答案(這是我所期望的)。 不正確的回應:

"response": {
    "data": {
      "message": "{\"0\": {\"0\": {\"Item\": \"Desinfetante 5L Max Talco Azul\", \"Qtd\": 2, \"UM\": \"GL\", \"Qtd_UM\": \"5L\", \"Qtd_Ttl\": \"10L\"}, \"1\": {\"Item\": \"Caf\\u00e9 A V\\u00e1cuo Tradicional 500G\", \"Qtd\": 10, \"UM\": \"PC\", \"Qtd_UM\": \"500g\", \"Qtd_Ttl\": NaN}}}"
    },
    "headers": {
      "content-type": [
        "application/json"
      ],
      "content-length": [
        "227"
      ],
      "access-control-allow-origin": [
        "*"
      ],
      "server": [
        "Werkzeug/1.0.1 Python/3.8.6"
      ],
      "date": [
        "Fri, 11 Dec 2020 13:16:32 GMT"
      ]
    },
    "status": 200,
    "statusText": "OK"
  }
}

預期的響應(僅數據輸入):

"response": {
    "data": {
      "0": {
        "0": {
          "Pedido": 997,
          "Qtd": 5,
          "Item": "Água Sanitária 1 Litro",
          "Fornecedor": "YYYY"
        },
        "1": {
          "Pedido": 997,
          "Qtd": 2,
          "Item": "Limpa Vidros Audax Facilita 500ml",
          "Fornecedor": "XXXX"
        }}}

當我直接從 python 發帖時,如下所示:

import requests
files = {'file': open('<path_to_file>','rb')}
r = requests.post(url="<url>/upload", files = files)
r.json()
Out[12]: 
{'0': {'0': {'Item': 'Desinfetante 5L Max Talco Azul',
   'Qtd': 2,
   'UM': 'GL',
   'Qtd_UM': '5L',
   'Qtd_Ttl': '10L'},
  '1': {'Item': 'Café A Vácuo Tradicional 500G',
   'Qtd': 10,
   'UM': 'PC',
   'Qtd_UM': '500g',
   'Qtd_Ttl': nan}}}
r.text
Out[16]: '{"0": {"0": {"Item": "Desinfetante 5L Max Talco Azul", "Qtd": 2, "UM": "GL", "Qtd_UM": "5L", "Qtd_Ttl": "10L"}, "1": {"Item": "Caf\\u00e9 A V\\u00e1cuo Tradicional 500G", "Qtd": 10, "UM": "PC", "Qtd_UM": "500g", "Qtd_Ttl": NaN}}}'

我每次都得到預期的 json 響應,即使使用相同的文件和標頭,也無法重現我在 react 中遇到的問題。

嘗試的事情:

  • 返回 json.dumps(result)
  • 返回 jsonify(resutl)
  • 返回響應

我發現您的響應數據具有\\"Qtd_Ttl\\": NaN (在您收到的意外響應中),這是無效的字符串格式,並且無法解析為 JSON。

所以如果你的數據有一個有效的鍵值“Qtd_Ttl”,那么你會得到預期的結果,如果值無效,你會得到帶有message鍵的響應。

這就是您在前端獲得奇怪格式的原因。 我認為您在前端使用 Axios。 如果您使用的是 Axios,我發現當來自服務器的 JSON 響應無效時會發生這種情況,請使用像https://jsonlint.com/這樣的 JSON 驗證器來確保您的 JSON 格式正確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM