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

Variables getting refreshed with HTML POST operation in Flask

我正在尝试在 Flask 中为我的联系页面构建一个简单的数字验证码。联系人页面端点以 GET 模式加载并初始化验证码验证的值。当我以 POST 模式提交表单时,我希望用户输入的表单值与验证码值匹配。但是,它没有按预期工作。我使用 print 语句进行了一些故障排除,以查看值如何变化,并且验证码变量似乎正在使用 POST 操作重新初始化。有人可以建议解决方法吗?我的 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

这是 2 个随机数,您正在创建 cap_prod。您没有在任何地方保存 cap_prod。当 POST 请求到来时,您正在重新计算它(这次它将是 2 个新的随机数)

GET时创建的验证码需要先保存,等POST来的时候,与原来发送的值进行比较。

如果您将来要支持 refresh-captcha 图片(您需要调用 API 来生成新的验证码并保存)

我找到了解决方案,方法是将验证码变量存储在 Flask 的会话字典中,并在 re-initialising 值之前检查其是否存在。

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

可以在 Fadmeter.com and FadURL.com.

找到上述解决方案的工作示例