簡體   English   中英

從 flask 中的 class 方法返回 json 響應

[英]return a json response from a class method in flask

我有一個 class,它使用幾種方法處理數據庫中的更改,在每種方法中,我對數據進行某種驗證以檢查它是否可接受,如果不可接受,它將返回一個帶有錯誤和狀態的jsonfiy響應代碼:

class ChangeData():
# more code...
    def change_data(self, new_data):

        if new_data not valid:
            print({"error": "first name can only contain latters"})# will print if not valid
            return jsonify({"error":
                            "can't change the data"}), 400

        else:
            #change the data

我期待如果數據無效,它將返回到前端 jsonfiy 錯誤消息,但盡管打印有效,前端沒有收到 jsonfiy 錯誤,無論數據是否有效,它都會收到 jsonfiy 成功消息。

@app.route("/change", methods=["POST"])
def change_user_data():

    data = request.form

    update_data = ChangeData()

    new_data = data.get("new_data", None)


    if new_data:
        update_data.change_data(new_data)
    

    return jsonfiy({"sucsees": "the data as been changed"}), 200

我可以解決它的一種方法是,如果數據無效, change_data方法返回False ,如果有效,則返回True ,並基於此從“/change”路由返回一個 jsonfiy,但我不喜歡這個解決方案,提前致謝!

  1. 您的調用代碼不期望返回,因此您的錯誤不會在從 function 返回時被“捕獲”
if new_data:
        update_data.change_data(new_data)
  1. 即使您的調用代碼需要返回值,您也不會在向客戶端返回 output 之前檢查是否發生錯誤。 您的代碼只是
return jsonfiy({"success": "the data as been changed"}), 200
  1. 一種可能的解決方案是將調用代碼放在 try except 塊中,並從被調用方引發異常。 像這樣(這是一個粗略的輪廓,你必須充實它)
class ChangeData():
    def change_data(self, new_data):

        if new_data not valid:
            print({"error": "first name can only contain letters"})
            raise Exception("first name can only contain letters")
@app.route("/change", methods=["POST"])
def change_user_data():

    data = request.form
    update_data = ChangeData()
    new_data = data.get("new_data", None)

    try:
        if new_data:
            update_data.change_data(new_data)
        return jsonfiy({"sucsees": "the data as been changed"}), 200

    except:
        return jsonify({"error": "can't change the data"}), 400
        

暫無
暫無

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

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