python - 如何在 Flask 上返回 400(错误请求)?

标签 python api http flask bad-request

我创建了一个简单的 flask 应用程序,我正在读取来自 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...') 

这会在终端上打印消息:

enter image description here

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

enter image description here

代码结构如下:

|--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 消息错误。

最佳答案

您有多种选择:

最基本的:

@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

进一步阅读:

您可以在这里阅读更多关于前两个的信息:About Responses ( flask 快速入门)
第三个在这里:Status codes ( flask API 指南)

关于python - 如何在 Flask 上返回 400(错误请求)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57664997/

相关文章:

python - 文件数据到数组正在使用大量内存

java - 在 Windows 上访问智能卡时重用 Java Keystore

java - Spring MVC Controller 更改 URL 或发出错误的 URL

php - API (REST) 过滤表名、复杂查询

python - 带字典的点积

python - Pandas 数据框根据嵌套 if 条件设置列值

javascript - 是否有一些库可用于 IQR 代码(不是 QR 代码)?

json - Spring MVC : post request and json object with array : bad request

python - 将 Pandas 中事件的时间序列的列中的值序列转换为行

android - Youtube API 视频在非全屏时停止