首页 > 解决方案 > 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 个”

标签: pythonpython-3.xflaskurl-for

解决方案


您需要让第二个端点带有路径变量,并给出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)

看看这个其他问题可能会更清楚一点。


推荐阅读