简体   繁体   中英

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 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.

@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!

  1. Your calling code doesn't expect a return so your error is not being 'captured' on return from the 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. 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. 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
        

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM