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

Flask技术问题:如何将文件索引/名称从archive路由传递到delete路由

解决Flask视频归档项目中删除按钮传递参数的问题

核心问题分析

当前代码存在两个关键问题:

  • 表单action硬编码IP地址,路径生成不规范
  • 试图将循环变量idx作为按钮name属性,但HTML中name是静态字符串,且提交按钮的value用于显示文字,无法同时传递索引/文件名和保持按钮显示"Delete"

解决方案

通过隐藏表单字段传递文件名(比索引更可靠,避免文件列表变动导致索引对应错误),同时修正路由路径生成方式:

修改后的archive函数代码

from flask import url_for  # 确保导入url_for

@app.route('/archive' , methods=['GET', 'POST'])
def archive():  
    path = "/home/pi/Videos/"
    dir_list = os.listdir(path) 
    dir_list.sort()               # 排序文件列表
    

    output = '''<!DOCTYPE html><html lang="en">
<head>
    <!-- 这里放置你的样式代码 -->
</head>
<body>
    <div class="Box">
        <div class="flex-box">'''
    
    for file in dir_list:              # 循环遍历每个文件
        # 用隐藏字段传递文件名,表单action通过url_for生成正确路由
        output += f'''
        <div style='background: black;'>{file}</div>
        <form method='post' action='{url_for('delete_file')}'>
            <input type='hidden' name='file_name' value='{file}'>
            <input class='btn' type='submit' value='Delete'>
        </form>
        ''' 
    output += '''
        </div>
    </div>
</body>
</html>'''
    return output

修改后的delete_file函数代码

from flask import request, redirect, url_for
import os

@app.route('/delete', methods=['POST'])  # 删除操作仅需POST方法
def delete_file():
    file_name = request.form.get('file_name')
    if not file_name:
        # 未传递文件名时直接返回归档页面
        return redirect(url_for('archive'))
    
    # 拼接完整文件路径,同时做安全验证防止路径遍历攻击
    target_dir = "/home/pi/Videos/"
    file_path = os.path.join(target_dir, file_name)
    # 验证文件确实在目标目录内且存在
    if os.path.abspath(file_path).startswith(os.path.abspath(target_dir)) and os.path.exists(file_path):
        os.remove(file_path)
    
    return redirect(url_for('archive'))

关键改动说明

  • 隐藏字段传参:添加<input type='hidden' name='file_name' value='{file}'>,在不影响按钮显示的前提下传递文件名
  • 路由路径优化:用url_for('delete_file')自动生成正确的/delete路径,避免硬编码IP导致的错误
  • 安全防护:通过os.path.abspath验证文件路径范围,防止攻击者构造恶意文件名删除系统其他文件
  • 逻辑简化:直接传递文件名,无需依赖索引,避免文件列表变动引发的匹配错误

内容的提问来源于stack exchange,提问作者Kevin Keller

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 11:52:52