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

如何通过HTML按钮触发Python Flask函数并展示结果到前端页面

实现方案

整个功能通过「后端提供生成密码接口 + 前端异步请求接口渲染结果」实现,点击按钮不需要刷新页面,具体修改步骤如下:

1. 修改后端Flask逻辑

你原来的passGen()用print()只会把密码输出到后端控制台,没法传给前端,需要调整函数返回值,同时新增专门的接口响应前端的生成请求:

from flask import Flask, render_template, jsonify
import string
import random

app = Flask(__name__)

# 调整密码生成函数,直接返回生成结果
def passGen():
    letras = string.ascii_letters
    numeros = string.digits
    especiais = string.punctuation
    tam = random.randrange(7,13)
    char_pool = letras + numeros + especiais
    pass_random = "".join(random.sample(char_pool, tam))
    return pass_random

# 首页路由,返回你的HTML页面
@app.route('/')
def index():
    # 注意:HTML文件需要放在项目根目录的templates文件夹下
    return render_template('index.html')

# 新增密码生成接口,只接受GET请求
@app.route('/generate-pass', methods=['GET'])
def gen_pass_api():
    new_password = passGen()
    return jsonify({"password": new_password})

if __name__ == '__main__':
    app.run(debug=True)

2. 修改前端HTML代码

给按钮和密码展示标签加唯一标识,绑定点击事件,点击时请求后端接口拿到密码后直接渲染到页面:

<html>
<head>
    <meta charset='utf-8'>
    <title>Meu Site</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel="stylesheet" href="{{ url_for('static', filename= 'CSS/style.css') }}">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
    <div class="container mt-5">
        <!-- 给按钮加id,用于绑定点击事件 -->
        <input type="button" value="gerarSenha" id="genPassBtn" class="btn btn-primary btn-lg btn-block">
    </div>
    
    <h1 class="text-center mt-4">
        <!-- 给展示密码的标签加id,用于后续填充内容 -->
        <p id="passDisplay"></p>
    </h1>

    <script>
        const genBtn = document.getElementById('genPassBtn');
        const passBox = document.getElementById('passDisplay');

        // 绑定按钮点击事件
        genBtn.addEventListener('click', async () => {
            try {
                // 异步请求后端接口
                const resp = await fetch('/generate-pass');
                const result = await resp.json();
                // 将返回的密码填充到页面
                passBox.textContent = result.password;
            } catch (e) {
                passBox.textContent = "密码生成失败,请重试";
            }
        })
    </script>
</body>
</html>

注意事项

  • Flask默认会从根目录下的templates文件夹读取模板文件,从static文件夹读取静态资源,你需要把现有HTML文件移到templates目录,CSS文件放到static/CSS/路径下,否则会报404错误
  • 不要在密码生成逻辑里加print()输出,生成的密码必须通过路由返回给前端,否则前端拿不到结果
  • 这里用原生fetch实现异步请求,不需要引入额外的第三方库,点击按钮不会触发整页刷新,交互更流畅

内容的提问来源于stack exchange,提问作者Leonardo Sallin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 16:09:20