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

