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
相关产品推荐
相关产品推荐

