在烧瓶中使用`redirect`和`url_for`时出现404

时间:2020-02-21 02:09:32

标签: flask

我正在尝试测试烧瓶中的重定向。我可以直接转到端点url没问题,但是当我尝试重定向到它时,出现一条错误消息。

编辑:我将方法,调用和url的名称更改为'predict',但仍然遇到相同的错误。

这是我的代码的样子

from flask import Flask, request, render_template, jsonify
from flask_ngrok import run_with_ngrok
from flask import redirect, url_for

app = Flask(__name__)
run_with_ngrok(app)

@app.route('/QueryParser', methods=['GET', 'POST'])
def query():

    if request.method == 'GET':
        return render_template('index.html', value='hi')
    else:
        body = request.get_json()

        question_textN = body['question']
        context_textN = body['context']

        return redirect(url_for('predict', question=question_textN, 
                        context=context_textN))

@app.route("/predict/<question>/<context>", methods=["GET"])
def predict(question, context):

    question_text = question
    context_text = context

    return jsonify(answer=question_text, context=context_text)

if __name__=="__main__":
    app.run()

在此特定实例上,其运行于

http://688adffe.ngrok.io/QueryParser

当我放入上下文并进行查询并单击“询问”时,什么也没有发生,我在命令行输出中看到了这一点

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Running on http://688adffe.ngrok.io
 * Traffic stats available on http://127.0.0.1:4040
127.0.0.1 - - [21/Feb/2020 03:51:48] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [21/Feb/2020 03:51:48] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [21/Feb/2020 03:51:55] "GET /QueryParser HTTP/1.1" 200 -
127.0.0.1 - - [21/Feb/2020 03:52:01] "POST / HTTP/1.1" 404 -

如果我直接转到url,它就可以正常工作

http://688adffe.ngrok.io/predict/test1/test2

我在命令行输出中得到了

127.0.0.1 - - [21/Feb/2020 02:07:28] "GET /ModelInference/test1/test2 HTTP/1.1" 200 -

有一个输出(尽管我的目的是将输出传递给html,但我稍后可以担心)

{
  "answer": "test1", 
  "context": "test2"
}

要重新创建最小示例,请使用此代码从我的Google驱动器下载文件。请注意,高于1.0的烧瓶版本有时无法与flask_ngrok一起使用。在某些情况下,仅0.12.5或0.12.4版本有效。

!pip install flask==1.0
!pip install flask-ngrok
import os
if not os.path.exists('templates'):
    os.mkdir('templates')

%cd templates
!gdown --id 1-l3SlwyyNjSV-bzUnyw1ZpPaPQz3KUYP
%cd ..
!gdown --id 1s_lGCf_T0619RWZKBjQ_oES0jwmNSn2F

!python rest-testMin.py

为方便起见,这是一个Google colab链接,此代码可随时执行

https://colab.research.google.com/drive/1uxbR0-c75njIq5dckSpKVaklZkrTb4kf

1 个答案:

答案 0 :(得分:1)

url_for的第一个参数应该是视图函数的名称。应该是

return redirect(url_for('predict', question=question_textN, context=context_textN))

Docs

flask.url_for(端点,**值)

使用提供的方法生成指向给定端点的URL。

从服务器输出中

127.0.0.1 - - [21/Feb/2020 03:52:01] "POST / HTTP/1.1" 404 -

似乎您没有正确设置表单action属性以指向查询视图功能。

<form method="post" action="{{url_for('query')}}">
...
</form>