You need to enable JavaScript to run this app. 如何在Flask应用中实现动态循环表单收集多组用户输入运行Python脚本
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask应用中实现动态循环表单收集多组用户输入运行Python脚本

极简Flask单页应用全实现方案

项目最简结构

  • 根目录放置后端入口文件app.py
  • 根目录创建templates文件夹,存放唯一的页面文件index.html
    无额外静态资源、无复杂依赖,完全匹配“极简单页”的定位。

后端逻辑实现

核心原则:不修改你已有的Goodreads检索核心代码shared_books,只做参数接收和页面渲染,替代原来的命令行参数收集流程。
app.py完整代码如下:

from flask import Flask, render_template, request
# 导入你原有脚本编写完成的检索核心函数,函数内部逻辑完全不需要改动
# from your_goodreads_tool import shared_books

app = Flask(__name__)

@app.route('/')
def index():
    # 直接返回单页模板,无额外预处理逻辑
    return render_template('index.html')

@app.route('/run-search', methods=['POST'])
def run_search():
    # 读取用户提交的列表总数量
    total_list_count = int(request.form.get('total_count'))
    collected_list_params = []
    # 按序号批量收集每个列表的URL、页数参数,完全等价原命令行循环收集的逻辑
    for idx in range(1, total_list_count + 1):
        target_url = request.form.get(f'list_url_{idx}')
        crawl_page = int(request.form.get(f'list_page_{idx}'))
        collected_list_params.append((target_url, crawl_page))
    # 直接把结构化参数传入原有核心检索函数,不需要适配函数接口
    search_result = shared_books(collected_list_params)
    # 把检索结果传回当前页面渲染,全程不跳转
    return render_template('index.html', results=search_result)

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

前端交互实现(完全替代原命令行循环输入)

整个页面采用原生无刷新交互,流程和原命令行逻辑1:1对齐:

  1. 首先展示独立输入区,引导用户输入待检索列表总数量
  2. 校验输入为正整数后,触发按钮动态生成对应数量的输入组,每组包含列表URL、检索页数两个输入项,等价于原脚本的for循环逐次收集输入
  3. 所有输入项生成完成后,自动切换到提交表单视图,用户填完参数直接触发检索

templates/index.html完整代码如下:

<!DOCTYPE html>
<html>
<head>
    <title>Goodreads跨列表共享书籍检索</title>
</head>
<body>
    <h1>Goodreads共享书籍检索工具</h1>

    <!-- 第一步:输入列表总数量的区域 -->
    <div id="count-input-area">
        <label>请输入待检索的Goodreads列表总数量:</label>
        <input type="number" id="total_count" min="1" required>
        <button type="button" id="generate-inputs">生成输入项</button>
    </div>

    <!-- 动态生成的列表输入项承载区 -->
    <form id="search-form" action="/run-search" method="POST" style="display: none;">
        <div id="dynamic-input-container"></div>
        <input type="hidden" name="total_count" id="hidden_total_count">
        <button type="submit">开始检索</button>
    </form>

    <!-- 检索结果展示区 -->
    {% if results %}
    <div id="result-area">
        <h2>检索结果</h2>
        <ul>
            {% for item in results %}
            <li>{{ item }}</li>
            {% endfor %}
        </ul>
    </div>
    {% endif %}

    <script>
        const generateBtn = document.getElementById('generate-inputs');
        const countInput = document.getElementById('total_count');
        const dynamicContainer = document.getElementById('dynamic-input-container');
        const searchForm = document.getElementById('search-form');
        const hiddenTotalField = document.getElementById('hidden_total_count');

        generateBtn.addEventListener('click', () => {
            const inputCount = parseInt(countInput.value.trim());
            // 基础输入校验
            if (isNaN(inputCount) || inputCount < 1) {
                alert('请输入有效的正整数列表数量');
                return;
            }
            // 清空历史生成的旧输入组,避免重复提交
            dynamicContainer.innerHTML = '';
            // 循环生成对应数量的输入组,替代原命令行for循环收集逻辑
            for (let seq = 1; seq <= inputCount; seq++) {
                const inputWrap = document.createElement('div');
                inputWrap.innerHTML = `
                    <h3>第${seq}个列表</h3>
                    <label>列表URL:</label>
                    <input type="url" name="list_url_${seq}" required>
                    <label style="margin-left: 15px;">检索页数:</label>
                    <input type="number" name="list_page_${seq}" min="1" value="1" required>
                    <hr>
                `;
                dynamicContainer.appendChild(inputWrap);
            }
            // 缓存输入的总数量,切换到表单视图
            hiddenTotalField.value = inputCount;
            document.getElementById('count-input-area').style.display = 'none';
            searchForm.style.display = 'block';
        })
    </script>
</body>
</html>

关键适配要点

  • 动态生成的输入项采用统一命名规则,后端可按序号批量采集,收集到的参数结构和原命令行流程下的格式完全对齐,传入shared_books即可直接运行
  • 原脚本里所有input()、循环采集命令行参数的代码可以全部删除,无保留必要
  • 校验逻辑分两层:前端做快速输入拦截,后端做二次格式校验,避免无效参数打断检索流程
  • 检索结果直接在当前页面渲染,不做页面跳转,保持单页操作体验

内容的提问来源于stack exchange,提问作者Ishan Deulkar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.29 01:06:10