
本文介绍如何通过 Flask 的 URL 变量路由机制,将文件名从 /archive 页面准确、安全地传递至 /delete 路由,避免表单字段命名冲突与数据丢失问题,并结合 Jinja2 模板实现清晰可维护的前端渲染。
本文介绍如何通过 flask 的 url 变量路由机制,将文件名从 `/archive` 页面准确、安全地传递至 `/delete` 路由,避免表单字段命名冲突与数据丢失问题,并结合 jinja2 模板实现清晰可维护的前端渲染。
在 Flask Web 开发中,直接拼接 HTML 字符串(如使用 output += ...)不仅难以维护,还容易引发 XSS 风险和逻辑错误——尤其当需要动态绑定按钮行为(如删除特定视频)时,传统 <input name="idx" value="Delete"> 方式无法可靠传递索引或文件名,因为所有按钮 name 相同,request.form['idx'] 仅返回固定字符串 "Delete",而非实际目标文件。
推荐采用 URL 路径参数 + RESTful 设计 的方式替代表单字段传值:将待删文件名作为路径变量嵌入 action URL,既语义清晰,又无需依赖表单 name/value 匹配,彻底规避歧义。
以下为优化后的完整实现:
from flask import Flask, redirect, render_template_string, url_for
import os
app = Flask(__name__)
@app.route('/archive')
def archive():
path = '/home/pi/Videos/'
try:
dir_list = sorted(os.listdir(path))
except OSError as e:
dir_list = []
print(f"Warning: Cannot read directory {path}: {e}")
return render_template_string('''
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Video Archive</title></head>
<body>
<div class="box">
<div class="flex-box">
{% for file in dir_list %}
<div style="background: #1a1a1a; padding: 12px; margin: 4px 0; border-radius: 4px;">
<strong>{{ file }}</strong>
<form method="post" action="{{ url_for('delete', filename=file) }}" style="display:inline;">
<button type="submit" class="btn" style="margin-left: 8px; background:#e74c3c; color:white; border:none; padding:6px 12px; border-radius:4px; cursor:pointer;">
Delete
</button>
</form>
</div>
{% else %}
<p>No videos found.</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/skill5360" title="Skill Weave Chains — 技能链路由引擎"><img
src="https://img.php.cn/upload/skill/000/000/081/179047814579604.jpg" alt="Skill Weave Chains — 技能链路由引擎" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/skill5360" title="Skill Weave Chains — 技能链路由引擎">Skill Weave Chains — 技能链路由引擎</a>
<p>开箱即用的技能链路由引擎。13 条预定义链覆盖搜索、开发、审查、MLOps、法律、创意等场景,三层路由架构(触发词→SAD反馈→DAG编排),recall@10=96.97%。配置驱动(chains.yaml),零代码扩展。pip install skill-weave-chains 一键安装。</p>
</div>
<a href="/xiazai/skill5360" title="Skill Weave Chains — 技能链路由引擎" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div>
{% endfor %}
</div>
</div>
</body>
</html>
''', dir_list=dir_list)
@app.post('/delete/<path:filename>')
def delete(filename):
safe_path = '/home/pi/Videos/'
target_file = os.path.join(safe_path, filename)
# 关键防护:防止路径遍历攻击(如 filename="../../etc/passwd")
if not os.path.abspath(target_file).startswith(os.path.abspath(safe_path)):
return "Invalid file path", 400
try:
if os.path.isfile(target_file):
os.remove(target_file)
print(f"Deleted: {target_file}")
else:
print(f"Skipped (not a file): {target_file}")
except PermissionError:
return "Permission denied", 403
except Exception as e:
print(f"Deletion failed: {e}")
return "Error deleting file", 500
return redirect(url_for('archive'))✅ 关键改进说明:
-
语义化路由:
@app.post('/delete/<filename>')</filename>显式声明filename为 URL 参数,Flask 自动注入到视图函数;<...></...><...></...> -
-
-
-
<button type="submit"></button><input>


















