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

如何为Flask路由添加URL参数自动填充HTML输入框实现API功能

Flask实现URL传参自动填充Input+接口化改造方案

一、先修复原有代码的已知问题

原有代码存在2处逻辑错误:

  • 判断if 'link' != ''是固定为真的无效判断,实际应该判断表单提交的link字段是否非空
  • 函数缩进错误,return语句要放在函数内部

二、两种传参实现方案

方案1:路径参数(匹配你给出的示例调用格式)

1. 修改Flask路由代码

import webbrowser
from flask import request, render_template

@app.route('/link/', defaults={'pre_fill': None}, methods=['GET', 'POST'])
@app.route('/link/<pre_fill>', methods=['GET', 'POST'])
def open_link():
    # 支持直接当API调用:带参数直接打开链接,无需提交表单
    if request.method == 'GET' and pre_fill is not None:
        webbrowser.open(pre_fill)
        # 也可以自定义返回响应内容
        return {"status": "success", "opened_link": pre_fill}
    
    if request.method == "POST":
        text = request.form.get('link', '').strip()
        if text:
            webbrowser.open(text)
            return {"status": "success", "opened_link": text}
    # 渲染页面时把预填参数传给模板
    return render_template("get_link.html", pre_fill=pre_fill)

2. 修改HTML模板,给input加预填值

<HTML>
   <body>
       <form method=post enctype=multipart/form-data>
           <input type=text name=link value="{{ pre_fill if pre_fill else '' }}">
           <input type=submit value=Open>
       </form>
   </body>
</HTML>

调用示例

http://192.168.5.107:8000/link/https://www.baidu.com

访问该链接会直接打开对应网址,同时如果用户需要手动编辑的话,input框会自动填充参数值。


方案2:查询参数(更符合标准API设计规范)

1. 修改Flask路由代码

import webbrowser
from flask import request, render_template

@app.route('/link', methods=['GET', 'POST'])
def open_link():
    pre_fill = request.args.get('link', None)
    # 直接API调用逻辑
    if request.method == 'GET' and pre_fill is not None:
        webbrowser.open(pre_fill)
        return {"status": "success", "opened_link": pre_fill}
    
    if request.method == "POST":
        text = request.form.get('link', '').strip()
        if text:
            webbrowser.open(text)
            return {"status": "success", "opened_link": text}
    return render_template("get_link.html", pre_fill=pre_fill)

2. HTML模板修改逻辑和方案1完全一致

调用示例

http://192.168.5.107:8000/link?link=https://www.baidu.com

补充说明

如果不需要直接自动打开链接,只需要填充input框,删掉路由中GET请求的自动打开逻辑即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 20:18:03