python - TypeError: url_for() 接受 1 个位置参数,但给出了 2 个
问题描述
如果 x=俄亥俄
我想将用户重定向到 /weather/ohio
我能去上班的只是 /weather/?x=ohio
我这样做是为了运行第二条路线@app.route("/weather/")。我不确定我错过了什么。这是加载/weather/ohio 的最佳方式吗,其中ohio 是从表单加载的变量。
@app.route("/weather/", methods = ['POST', 'GET'])
def weather():
if request.method == 'POST':
x = request.form['search_location']
return redirect(url_for('weather', x=x))
#print (y)
else:
return render_template("weather.html")
如果我把 x= 拿出来,我会得到错误“TypeError:url_for() 需要 1 个位置参数,但给出了 2 个”
解决方案
您需要让第二个端点带有路径变量,并给出url_for()
与端点关联的函数的名称:
@app.route("/weather", methods = ["POST", "GET"])
def weather():
if request.method == "POST":
x = request.form["search_location"]
return redirect(url_for("weather_location", x=x))
else:
return render_template("weather.html")
@app.route("/weather/<x>")
def weather_location(x):
return "It's always sunny in {}".format(x)
看看这个其他问题可能会更清楚一点。
推荐阅读
- python - 如何在sklearn中输出决策树数据
- cordova - Cordova 无需录音机即可录制音频
- vue.js - 与同一 App.js 中的另一个组件共享来自一个组件的数据
- ruby - 使用 Object.send(:remove_const, 'MyClass') 的 Ruby 问题
- jenkins - 中止的詹金斯管道作业继续运行后期
- java - 通过 getter 和 setter 更新 pojo 的通用方法
- android - 无法在 android studio 中解析 default_web_client_id
- python - 加深对 Python read() 和 open() 函数的理解
- javascript - 在 React 中动态更新“状态”会覆盖整个状态
- angular - 填充数组并使其可使用 Angular Material 过滤