Variables getting refreshed with HTML POST operation in Flask

dqsbl2010 注册会员
2023-01-25 12:42
cap_a = random.randint(0, 9)
cap_b = random.randint(0, 9)
cap_prod = cap_a * cap_b

these are 2 random numbers and you are creating cap_prod. You are not saving the cap_prod anywhere. You are instead calculating it again when POST request comes (this time it will be 2 new random numbers)

You need to save the captcha that you created during the GET, and then when the POST comes , compare with the value that was originally sent.

If you are going to support refresh-captcha image in the future (you need to have an API call that will generate a new captcha and save it)

chentongli0577 注册会员
2023-01-25 12:42

I figured out the solution by storing the captcha variables in the session dictionary of Flask and checking for its existence before re-initialising the values.

def contact():
    # Initialize captcha values
    if 'product' not in session:
        cap_a = random.randint(0, 9)
        cap_b = random.randint(0, 9)
        session['captcha_a'] = cap_a
        session['captcha_b'] = cap_b
        session['product'] = cap_a * cap_b
        cap_a = session.get('captcha_a')
        cap_b = session.get('captcha_b')
    if request.method == "POST":
        # Rest of the code

Working examples of the above solution can be found at Fadmeter.com and FadURL.com.