gpt4 book ai didi

python - 引入 flask_restful 后,flask errorhandler 在 gunicorn 中不起作用

转载 作者:行者123 更新时间:2023-11-28 19:15:27 24 4
gpt4 key购买 nike

我正在 flask 中开发 REST API,并计划在 Gunicorn 中运行它。在我的应用程序中,用户定义的异常由 flask errorhandler 装饰器处理。它在 flask 内置 Web 服务器和 Gunicorn 中都运行良好。响应可以从修饰函数生成。引入flask_restful后,内置服务器工作正常,但在Gunicorn中,响应总是{"message": "Internal Server Error"}

这里是源代码:myapp.py

from flask import Flask, jsonify, make_response
from flask_restful import Api, Resource


app = Flask(__name__)
api = Api(app)


class OrderNotExistError(Exception):
def __init__(self, order_id):
self.message = 'Order [{order_id}] does not exist.'.format(order_id=order_id)


@app.errorhandler(OrderNotExistError)
def order_not_exist(error):
return make_response(jsonify({'message': error.message}), 404)


class OrderAPI(Resource):
def get(self, order_id):
raise OrderNotExistError(order_id)


api.add_resource(OrderAPI, '/orders/<int:order_id>', endpoint='order')


@app.route("/o/<int:order_id>")
def get_order(order_id):
raise OrderNotExistError(order_id)


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

在 Gunicorn 中运行:gunicorn -w4 -b0.0.0.0:8000 myapp:app

访问“http://127.0.0.1:8000/o/123
它回应:{“消息”:“订单 [123] 不存在。”}。错误处理程序工作正常。

访问“http://127.0.0.1:8000/orders/123
它回应:{“消息”:“内部服务器错误”}。似乎错误处理程序不起作用。

在flask内置服务器中运行,没有出现该问题。

有人遇到同样的问题吗?这是 flask_restful 或 Gunicorn 中的错误吗?如何处理这个问题?

最佳答案

这是因为有两个级别的错误处理程序,一个在应用程序级别,一个在 API 级别。您正在直接调用 api,因此该应用程序看不到它。 (这解释了为什么通过 app.route 添加的路由会捕获异常,而通过 api.add_resource 添加的路由不会捕获异常)。

要捕获此错误,您需要覆盖 Werkzeug 的异常,这是 flask-restful 使用的。下面的代码应该修复它:

errors={
'InternalServerError': {
'status': 500,
'message': 'Internal Server Error'
},
}
api = Api(app, errors=errors)

关于python - 引入 flask_restful 后,flask errorhandler 在 gunicorn 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34037283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com