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

Flask中如何在url_for中传递变量?替换静态文件路径固定值

Flask中用url_for传递变量替换静态文件路径

你可以直接在url_for的filename参数里通过字符串拼接或格式化,把表单输入的form.city.data值嵌入路径中,修改后的代码如下:

<div>
    <iframe height="800" width="100%" class="p-5 embed-responsive-item"
        src="{{ url_for('static', filename='videos/' + form.city.data + '.html') }}" allowfullscreen></iframe>
</div>

也可以用Jinja2支持的f-string写法:

<div>
    <iframe height="800" width="100%" class="p-5 embed-responsive-item"
        src="{{ url_for('static', filename=f'videos/{form.city.data}.html') }}" allowfullscreen></iframe>
</div>

关键提醒

  • 必须对form.city.data做合法性校验:要么限定为预设的城市名称列表,要么过滤掉../这类特殊字符,防止用户输入恶意路径引发路径遍历攻击,访问静态目录外的文件。
  • 要确保对应城市的静态文件(比如videos/london.html)确实存在于你的静态文件夹中,否则会返回404错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:26:05