1

I am implementing addcash function to finance and I have one issue with checking if input value is an integer value, the problem is whenever I input non-integer value for testing purposes my page breaks with error. Here is my code:

@app.route("/addcash", methods=["GET", "POST"])
@login_required
def addcash():
"""Add cash."""
if request.method == "POST":

    if request.form.get("addcash") == "":
        return apology("invalid input")


    addCash = int(request.form.get("addcash"))

    if not addCash:
        return apology("invalid input, please try again")

    db.execute("UPDATE users SET cash=cash+:addCash WHERE id = :user_id", user_id=session['user_id'], addCash=addCash)

    return redirect(url_for("index"))
else:
    return render_template("addcash.html")

The page gives me following error:

enter image description here

I also realized that my buy and sell functions also have this bug whenever inputing non-int value for testing purposes, how to fix this problem and return apology instead?

1

request.form.get("var") returns a string.

From the python doc for int():

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base. [x being the argument to int()]

If a decimal number is entered, then x will not be an "integer literal". You might want to investigate the python built-in float().

From the screen shot it looks like 'asd' was entered in the form. That's going to cause an error whether you use int() or float(). To prevent "garbage in" consider using a "numeric" type with a "step" attribute in the html. That way you don't have to write a whole bunch of python code to parse and cleanse user input. Here is the MDN doc on <input>.

Example: <input class="form-control" name="cash" placeholder="Cash" type="number" step=".01"/>

  • this is exactly what I need, thanks a lot – bobby_pin Apr 21 '17 at 6:07
0

I think you'll find Python's isdigit() method exactly what you need in order to validate the input.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .