You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReCaptcha v3本地运行正常但部署至PythonAnywhere后失效的问题求助

ReCaptcha v3本地运行正常但部署至PythonAnywhere后失效的问题求助

大家好,我现在在做个人作品集项目,想通过ReCAPTCHA v3来隐藏我的联系方式,避免收到垃圾信息。在本地环境下它运行完全正常,但部署到PythonAnywhere之后就失效了。我已经做了以下排查:

  • 确认存储密钥的环境变量配置正确,并且程序能正确读取到它
  • 手动用curl测试:用网站加载时生成的token和我的密钥调用验证接口,测试是成功的
  • 确认index.html里的站点密钥(site key)是正确的
  • 验证了我的域名已经在密钥的白名单里

另外还有个背景:最开始我把密钥硬编码后提交到了GitHub(现在想想真的蠢),后来收到了GitHub的警告邮件,于是我旋转了密钥,结果就卡在现在这个状态了——之前硬编码的时候部署到PythonAnywhere是正常的,换了密钥之后就不行了。

我把相关的代码片段贴在下面,希望有人能帮我看看问题出在哪,非常感谢!


index.html 相关代码

首先是head部分的ReCAPTCHA引入:

<head>
    <title>My Portfolio</title>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>
    <link rel="stylesheet" href="../static/assets/css/main.css"/>
    <script src="https://www.google.com/recaptcha/api.js?render=<SITE_KEY>"></script>
</head>

然后是前端验证逻辑的脚本:

<script>
        grecaptcha.ready(async function () {
            const token = await grecaptcha.execute('<SITE_KEY>', { action: 'contact_info' });

            // Verify the reCAPTCHA token with the server
            const response = await fetch('/verify_recaptcha', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ token: token })
            });

            const result = await response.json();
            if (result.success && result.score > 0.5) {
                document.getElementById('contact-info').style.display = 'block';
            } else {
                console.error('Failed reCAPTCHA verification');
            }
        });
    </script>

server.py 相关代码

@app.route('/verify_recaptcha', methods=['POST'])
def verify_recaptcha():
    try:
        data = request.json  # Expecting JSON payload
        token = data.get('token')


        # Send the token to Google's verification API
        verify_url = 'https://www.google.com/recaptcha/api/siteverify'
        payload = {'secret': secret_key, 'response': token}
        response = requests.post(verify_url, data=payload)
        result = response.json()

        # Add additional logging for debugging
        print(f"reCAPTCHA verification result: {result}")

        return jsonify({
            'success': result.get('success', False),
            'score': result.get('score', 0),
            'action': result.get('action', ''),
        }), 200
    except Exception as e:
        print(f"Error during reCAPTCHA verification: {e}")
        return jsonify({'success': False, 'error': 'Internal server error'}), 500

备注:内容来源于stack exchange,提问作者Jason Russo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 12:23:19