首页 > 解决方案 > 如何在 Flask 上返回 400(错误请求)?

问题描述

我创建了一个简单的烧瓶应用程序,我正在读取来自 python 的响应:

response = requests.post(url,data=json.dumps(data), headers=headers ) 
data = json.loads(response.text)

现在我的问题是,在某些情况下,我想返回 400 或 500 消息响应。到目前为止,我正在这样做:

abort(400, 'Record not found') 
#or 
abort(500, 'Some error...') 

这确实会在终端上打印消息:

在此处输入图像描述

但在 API 响应中,我不断收到 500 错误响应:

在此处输入图像描述

代码结构如下:

|--my_app
   |--server.py
   |--main.py
   |--swagger.yml

server.py这段代码在哪里:

from flask import render_template
import connexion
# Create the application instance
app = connexion.App(__name__, specification_dir="./")
# read the swagger.yml file to configure the endpoints
app.add_api("swagger.yml")
# Create a URL route in our application for "/"
@app.route("/")
def home():
    """
    This function just responds to the browser URL
    localhost:5000/

    :return:        the rendered template "home.html"
    """
    return render_template("home.html")
if __name__ == "__main__":
    app.run(host="0.0.0.0", port="33")

并且main.py具有我用于 API 端点的所有功能。

例如:

def my_funct():
   abort(400, 'Record not found') 

my_funct被调用时,我会Record not found在终端上打印出来,但不会在 API 本身的响应中,在那里我总是会收到 500 消息错误。

标签: pythonapihttpflaskbad-request

解决方案


您有多种选择:

最基本的:

@app.route('/')
def index():
    return "Record not found", 400

如果要访问标头,可以获取响应对象:

@app.route('/')
def index():
    resp = make_response("Record not found", 400)
    resp.headers['X-Something'] = 'A value'
    return resp

或者你可以让它更明确,不仅仅是返回一个数字,而是返回一个状态码对象

from flask_api import status

@app.route('/')
def index():
    return "Record not found", status.HTTP_400_BAD_REQUEST

进一步阅读:

您可以在此处阅读有关前两个的更多信息:关于响应(Flask 快速入门)
和第三个:状态代码(Flask API 指南)


推荐阅读