简体   繁体   English

从 flask 中的 class 方法返回 json 响应

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

I have a class that handles changes in the DB with a couple of methods, In each method, I am doing some sort of validation to the data to check if it's acceptable, and if not it will return a jsonfiy response with an error and status code:我有一个 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

I was expecting that if the data is not valid it will return to the frontend the jsonfiy error message but although the print works the frontend isn't receiving the jsonfiy error its receiving the jsonfiy success message no matter if the data is valid or not.我期待如果数据无效,它将返回到前端 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

One way I can solve it is by returning False from the change_data method if the data is not valid and True if it is, and based on that return a jsonfiy from the "/change" route, but I don't like this solution, Thanks in advance!我可以解决它的一种方法是,如果数据无效, change_data方法返回False ,如果有效,则返回True ,并基于此从“/change”路由返回一个 jsonfiy,但我不喜欢这个解决方案,提前致谢!

  1. Your calling code doesn't expect a return so your error is not being 'captured' on return from the function您的调用代码不期望返回,因此您的错误不会在从 function 返回时被“捕获”
if new_data:
        update_data.change_data(new_data)
  1. Even if your calling code expected a return value, you're not checking if an error occurred before returning an output to the client.即使您的调用代码需要返回值,您也不会在向客户端返回 output 之前检查是否发生错误。 Your code simply does您的代码只是
return jsonfiy({"success": "the data as been changed"}), 200
  1. One possible solution is to put your calling code within a try except block and raise an exception from the callee.一种可能的解决方案是将调用代码放在 try except 块中,并从被调用方引发异常。 Something like this (this is a rough outline and you have to flesh it out)像这样(这是一个粗略的轮廓,你必须充实它)
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