[英]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,但我不喜欢这个解决方案,提前致谢!
if new_data:
update_data.change_data(new_data)
return jsonfiy({"success": "the data as been changed"}), 200
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.