簡體   English   中英

Flask 視圖返回錯誤“視圖函數未返回響應”

[英]Flask view return error "View function did not return a response"

我有一個調用函數來獲取響應的視圖。 但是,它給出了錯誤View function did not return a response 我該如何解決?

from flask import Flask
app = Flask(__name__)

def hello_world():
    return 'test'

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

if __name__ == '__main__':
    app.run(debug=True)

當我嘗試通過添加靜態值而不是調用函數來測試它時,它起作用了。

@app.route('/hello', methods=['GET', 'POST'])
def hello():
    return "test"

以下不返回響應:

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

你的意思是說...

@app.route('/hello', methods=['GET', 'POST'])
def hello():
    return hello_world()

請注意在此固定函數中添加了return

無論在視圖函數中執行什么代碼,視圖都必須返回一個 Flask 識別為響應的值 如果函數沒有返回任何內容,則相當於返回None ,這不是有效的響應。

除了完全省略return語句之外,另一個常見錯誤是僅在某些情況下返回響應。 如果您的視圖基於iftry / except具有不同的行為,您需要確保每個分支都返回響應。

這個不正確的示例不會返回對 GET 請求的響應,它需要在if之后有一個 return 語句:

@app.route("/hello", methods=["GET", "POST"])
def hello():
    if request.method == "POST":
        return hello_world()

    # missing return statement here

這個正確的示例返回成功和失敗的響應(並記錄失敗以進行調試):

@app.route("/hello")
def hello():
    try:
        return database_hello()
    except DatabaseError as e:
        app.logger.exception(e)
        return "Can't say hello."

對不起,我的回答不是針對這個問題的。 最近我來到這里瀏覽標題中使用的相同錯誤消息,但之前的任何消息都回答了我的 Flask API 問題。

要返回使用requests模塊從另一個 API 檢索的 json、yaml、xml 等,您需要返回響應的文本,而不是requests模塊用來表示任何響應的類Response 例如:

# ❌ Wrong way to respond a response ❌
@server.route('/')
def home():
    import requests
    cats_response = requests.get('https://catfact.ninja/fact')

    return cats_response # 👈❌ Returns a class requests.models.Response
# ✔️ Right way to respond a response ✔️
@server.route('/')
def home():
    import requests
    cats_response = requests.get('https://catfact.ninja/fact')

    return cats_response.text # 👈✔️ Returns a string of the cats information

在此錯誤消息中,Flask 抱怨該function did not return a valid response 響應的強調表明它不僅僅是關於返回值的函數,而是一個有效的flask.Response對象,它可以打印消息、返回狀態代碼等。因此,可以這樣編寫簡單的示例代碼:

@app.route('/hello', methods=['GET', 'POST'])
def hello():
    return Response(hello_world(), status=200)

如果包含在 try-except 子句中,甚至更好:

@app.route('/hello', methods=['GET', 'POST'])
def hello():
    try:
        result = hello_world()
    except Exception as e:
        return Response('Error: {}'.format(str(e)), status=500)
    return Response(result, status=200)

暫無
暫無

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

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