为什么我的Flask app会重定向一条路线,即使我还没有将其配置为?

问题描述 投票:0回答:2

我正在尝试在Flask中编写一个POST路由,但每次我测试路由时,它都会使用301代码重定向相同的URL但作为GET请求。我不想要它,因为我需要POST主体。

我不明白为什么Flask这样做。

更令人困惑的是,在同一烧瓶应用程序中,有另一条路线不会重定向。

我还尝试仅将“POST”设置为允许的方法,但是路由仍然被重定向,并且响应是不允许的405方法,这是合乎逻辑的,因为我已经设置GET不是允许的方法。但是为什么它会重新定向并且自身重定向呢?

访问日志:

<redacted ip> - - [14/Feb/2019:11:32:39 +0000] "POST /service HTTP/1.1" 301 194 "-" "python-requests/2.21.0"
<redacted ip> - - [14/Feb/2019:11:32:43 +0000] "GET /service HTTP/1.1" 200 8 "-" "python-requests/2.21.0"

应用程序代码,请注意两个路径分别不做和重定向:

def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    @app.route('/path/does/not/redirect')
    def notredirected():
        url_for('static', filename='style.css')
        return render_template('template.html')

    @app.route('/service', strict_slashes=True, methods=["GET", "POST"])
    def service():
        return "Arrived!"

    return app

app = create_app()

我的预期结果是,POST /service将返回200并到达!作为其输出。

编辑:如果我将路由签名更改为:@app.route('/service', strict_slashes=True, methods=["POST"]),它仍然会重定向到GET请求,然后返回405,因为/ service没有GET路由。

<redacted> - - [14/Feb/2019:13:05:27 +0000] "POST /service HTTP/1.1" 301 194 "-" "python-requests/2.21.0"
<redacted> - - [14/Feb/2019:13:05:27 +0000] "GET /service HTTP/1.1" 405 178 "-" "python-requests/2.21.0"
python redirect flask
2个回答
1
投票

您的service路由已配置为处理GET和POST请求,但您的service路由不区分传入的GET和POST请求。默认情况下,如果未在路由上指定支持的方法,则flask将默认支持GET请求。但是,如果没有检查传入请求,则service路由不知道如何处理传入请求,因为GET和POST都受支持,因此它会尝试重定向以处理请求。一个简单的条件如下:if flask.request.method == 'POST':可用于区分两种类型的请求。话虽如此,也许你可以尝试以下内容:

@app.route('/service', methods=['GET', 'POST']) 
def service():
    if request.method == "GET":
        msg = "GET Request from service route"
        return jsonify({"msg":msg})
    else: # Handle POST Request
        # get JSON payload from POST request
        req_data = request.get_json()

        # Handle data as appropriate

        msg = "POST Request from service route handled"
        return jsonify({"msg": msg})

0
投票

问题是服务器将所有非https请求重定向到https变体,这是我不知道的。由于这对我们来说不是问题行为,因此解决方案是在客户端中指定使用https。

© www.soinside.com 2019 - 2024. All rights reserved.