簡體   English   中英

為什么我的Flask應用未配置為重定向一條路由?

[英]Why does my Flask app redirect one route even though I haven't configured it to?

我正在嘗試在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的路線。

<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"

您的service路由已配置為可以處理GET和POST請求 ,但您的service路由無法區分傳入的GET和POST請求 默認情況下,如果您在路由上未指定支持的方法,則flask將默認支持GET request 但是,由於不支持對傳入請求的檢查,因此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})

問題是服務器將所有非https請求都重定向到了我不知道的https變體。 由於這對我們來說不是問題,因此解決方案是在客戶端中指定使用https。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM