Python Flask错误“缺少必需的位置参数”(即使它们被提供)

时间:2017-11-22 01:49:18

标签: python flask

我有一个烧瓶索引路线,重定向到另一条路线,如下所示:

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        filepath="some/path/"
        top_1 = "something"
        top_2 = "somethingelse"
        top_3 = "somethingelse"
        return redirect(url_for('display_preds', filepath=filepath, 
                                      top_1=top_1, top_2=top_2, top_3=top_3), 
                                      code=307)

“display_preds”看起来像这样:

@app.route('/display_preds', methods=['GET', 'POST'])
def display_preds(filepath, top_1, top_2, top_3):
    if request.method == 'POST':
        return render_template("prediction.html")

最后在“prediction.html”页面中我有这个:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Test page</title>
</head>
<body>
    <h1>This is just a test</h1>
    <img src="{{ filepath }}" alt="some text">
    <br>
    <p> {{ top_1 }} </p> <br>
    <p> {{ top_2 }} </p> <br>
    <p> {{ top_3 }} </p>
</body>
</html>

执行此操作后,我可以看到redirect()具有“filepath”,“top_1”等值,因为我看到它尝试POST这样的事情:

address/display_preds?filepath=%2some%2file%2path&top_2=something&top_1=somethingelse&top_3=somethingelse

为什么我收到错误消息:

TypeError: display_preds() missing 4 required positional arguments: 'filepath', 'top_1', 'top_2', and 'top_3'

更新:

我尝试将路线更改为@app.route('/display_preds/<filepath>/<top_1>/<top_2>/<top_3>/', methods=['GET','POST'])但只是将错误更改为:

werkzeug.routing.BuildError: Could not build url for endpoint 'display_preds/filepath/top_1/top_2/top_3' with values ['filepath', 'top_1', 'top_2', 'top_3']. Did you mean 'display_preds' instead?

1 个答案:

答案 0 :(得分:0)

您在哪里提供render_template的值?

您可以使用像

这样的上下文字典

context = {"filepath": filepath, "top_1": top_1, "top_2":top_2, "top_3": top_3} render_template("prediction.html", context=context)

或直接在render_template中:

render_template("prediction.html", filepath=filepath, top_1=top_1, top_2=top_2, top_3=top3)

更新:您的重定向正在使用对新网址的GET请求,但在您的端点中,您没有使用request.args.get("top_1")检索参数。

def display_preds():
  filepath = request.args.get("filepath")
  top_1 = request.args.get("top_1")
  ....