简体   繁体   English

在 Flask 中使用 HTML POST 操作刷新变量

[英]Variables getting refreshed with HTML POST operation in Flask

I am trying to build a simple numeric captcha for my contact page in Flask. The contact page end-point loads in GET mode and initializes the values of the captcha verification.我正在尝试为 Flask 中的联系页面构建一个简单的数字验证码。联系页面端点以 GET 模式加载并初始化验证码验证的值。 When I submit the form in POST mode, I expect my user-entered form value to match the captcha value.当我以 POST 模式提交表单时,我希望用户输入的表单值与验证码值匹配。 However, it is not working as expected.但是,它没有按预期工作。 I did some troubleshooting with print statements to see how the values are changing and it appears that the captcha variables are getting re-initialised with the POST operation.我使用 print 语句进行了一些故障排除,以查看值是如何变化的,并且验证码变量似乎正在通过 POST 操作重新初始化。 Can someone please suggest a workaround?有人可以建议解决方法吗? My Python code is shared below:我的 Python 代码分享如下:

@bp.route('/contact/', methods=('GET', 'POST'))
def contact():
    # Initialize captcha values
    cap_a = random.randint(0, 9)
    cap_b = random.randint(0, 9)
    cap_prod = cap_a * cap_b
    print(cap_a, cap_b, cap_prod)
    if request.method == "POST":
        error = None
        log_file = current_app.config['LOGFILE']
        full_name = request.form['fullname']
        email_addr = request.form['email']
        phone_no = request.form['phone']
        msg_body = request.form['message']
        num_prod = request.form['verifycaptcha']
        print(cap_a, cap_b, cap_prod)
        print(full_name, email_addr, phone_no, msg_body, num_prod)
        if not full_name:
            error = 'Full name is required.'
        elif not email_addr:
            error = 'Email address is required.'
        elif not msg_body:
            error = 'Message body is required.'
        if num_prod != cap_prod:
            error = 'Incorrect captcha verification.'
        if error is None:
            # Perform some operations
            pass
            try:
                with current_app.app_context():
                    mail = Mail()
                    mail.init_app(current_app)
                    mail.send(msg)
                    error = 'Mail sent successfully!'
            except:
                error = 'Mail engine error encountered. Please retry after some time.'
                f = open(log_file, "a")
                f.write('['+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+'] '+error+'\n')
                f.close()
        flash(error)
    return render_template('contact.html',num_a = cap_a, num_b = cap_b)
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.这些是 2 个随机数,您正在创建 cap_prod。 You are not saving the cap_prod anywhere.您没有在任何地方保存 cap_prod。 You are instead calculating it again when POST request comes (this time it will be 2 new random numbers)当 POST 请求到来时,您将再次计算它(这次它将是 2 个新的随机数)

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.您需要保存您在 GET 期间创建的验证码,然后在 POST 到来时,与最初发送的值进行比较。

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)如果您将来要支持刷新验证码图像(您需要调用 API 来生成新的验证码并保存)

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.我通过将验证码变量存储在 Flask 的 session 字典中并在重新初始化值之前检查其存在来找到解决方案。

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
    else:
        cap_a = session.get('captcha_a')
        cap_b = session.get('captcha_b')
    if request.method == "POST":
        pass
        # Rest of the code

Working examples of the above solution can be found at Fadmeter.com and FadURL.com .可以在Fadmeter.comFadURL.com找到上述解决方案的工作示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM