0

Im making a script where a random number is used as a captcha when the template is loaded it creates a number but upon doing a post request and comparing the value that I entered with the captcha the number changes

Please note that this is not for production this is a test project

from flask import Flask,render_template,request
import random
app = Flask(__name__)
@app.route('/',methods=['GET', 'POST'])
def index():
    random_number = random.randint(100, 13337)
    print(random_number,"before POST")
    if request.method == 'POST':
        message = request.form['message']
        captcha=request.form['captcha']


        print(captcha,"after POST")

        if captcha == random_number:
            return '''<script>alert("Thank you ")</script>'''
            print(x)


    return render_template('index.html',random_number=random_number)
if __name__ == '__main__':
    app.run(debug=True)
index.html

<form method="POST">
    <div class="form-group">
    <label for="exampleInputPassword1">Message</label>
    <textarea type="text" class="form-control" id="exampleInputPassword1" placeholder="message" name="message"></textarea>
  </div>
  <div class="group">
    <label class="form-check-label" for="exampleCheck1">Verify that You are a human </label>
    <br>
    <label  class="captcha" for="exampleCheck1">{{ random_number }}</label>
    <div class="md-form form-group w-25">

        <input type="text" class="form-control" name="captcha" placeholder="Enter Captcha">
      </div>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

Rahul R
  • 11
  • 3
  • Probably because a new request is made and the new random number is generated ? how about sending the random number to the client side and validating it at the client side ? or to do it you need to maintain sessions to and a random variable for each user sessions. – venkata krishnan Jul 24 '19 at 07:33

1 Answers1

1

You will have to preserve your previous random number in the session or in DB, as in each request you r generating a new random number. Preserve the old random number, then only u can verify your captcha value against your Preserved value.

BTW On a note, I would recommend you instead of creating from scratch use some popular library for captcha validation such as https://pypi.org/project/flask-session-captcha/

trex
  • 3,848
  • 4
  • 31
  • 54