- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在 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/
我有以下 flak_restful 文件可将 csv 文件返回给用户,但出现以下错误。 File "/usr/local/Cellar/python3/3.6.1/Frameworks/Pytho
我有一个简单的带有 Flask-Restful 的 restful 应用 from flask import Flask from flask_restful import Api app = Fla
我正在尝试部署 appengine flex python 应用程序,但在部署后在 Stackdriver 日志 stderr 中获得以下信息 File "/env/local/lib/pytho
我设置了一个 flask_restful API,但希望用户在进行 post 调用时传递 numpy 数组。我第一次尝试使用 reqparse来自 flask_restful 但它不支持 numpy.
我有一个 flash/flask_result 应用程序设置如下。如何向整个应用程序添加自定义全局 404 错误消息?我应该用 Tornado 还是 flask 来做? from flask impo
Flask RESTApi 新手在这里 我正在尝试使用 .txt 在 Flask 中构建 RESTapi 服务(并且我正在尝试将输出保存为 flask_restful 文件)使用 pydifact 获
我正在 flask 中开发 REST API,并计划在 Gunicorn 中运行它。在我的应用程序中,用户定义的异常由 flask errorhandler 装饰器处理。它在 flask 内置 Web
我有以下非常简单的应用程序: from lib.flask import Flask from lib.flask_restful import Resource, Api app = Flask(_
我在 Flask 应用程序中遇到了这个错误: curl http://0.0.0.0:8080/ -H "Authorization: Bearer TGazPL9rf3aIftplCYDTGDc8c
我是一名优秀的程序员,十分优秀!