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

如何在Flask应用间重定向并传递URL查询参数?

解决方案

你的代码存在两个问题:一是视图函数定义了name参数但路由未提供对应变量,会导致请求报错;二是硬编码目标URL时没有携带原请求的查询参数。以下是两种实用的解决方法:

方法1:传递所有查询参数(通用方案)

直接获取原请求的完整查询字符串,拼接到目标URL后,这样不管有多少个查询参数都能一并传递:

from flask import Flask, redirect, request

app = Flask(__name__)

@app.route('/hello')
def hello_name():
    # 把字节类型的查询字符串解码为字符串,拼到目标URL后
    query_str = request.query_string.decode('utf-8')
    target_url = f"http://localhost:8000/hello?{query_str}" if query_str else "http://localhost:8000/hello"
    return redirect(target_url, 302)

方法2:传递指定查询参数(针对性方案)

如果只需要传递特定参数(比如仅name),可以单独提取参数后构造目标URL:

from flask import Flask, redirect, request

app = Flask(__name__)

@app.route('/hello')
def hello_name():
    name = request.args.get('name')
    # 有name参数就拼接,没有就直接跳转基础URL
    target_url = f"http://localhost:8000/hello?name={name}" if name else "http://localhost:8000/hello"
    return redirect(target_url, 302)

关键说明

  • 你提到的url_for()确实主要用于同Flask应用内的路由生成,跨应用跳转时直接拼接URL更简洁高效。
  • 原代码中视图函数的name参数需要移除,因为你的场景是通过查询参数传递name,而非路由路径参数,保留会导致请求时抛出TypeError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 09:15:59