how to not have the flask server break when an error occurs?

后端 未结 3 1950
粉色の甜心
粉色の甜心 2021-01-26 00:23

I have made an API app using flask, that takes a number(decimal) as input and returns some string. This app breaks if I send a string and works fine after re-starting it. I don\

3条回答
  •  故里飘歌
    2021-01-26 01:03

    You need to trigger a return with an error message, if whatever the user submits can't be expressed as an integer.

    The following should work for submissions like 3 and '3'

        # now the processing part
        try:
            number = int(json_data['number'])
        except ValueError:
            return jsonify(['Invalid submission'])
    
        # Number is now type integer
    
        if number < 2:
            return jsonify(["the number is less than two"])
        else:
            return jsonify(["the number is not less than two"])
    

提交回复
热议问题