2015-12-02 83 views
2

我正在烧瓶中开发REST API并计划在Gunicorn中运行它。 在我的应用程序中,用户定义的Exception由flask errorhandler装饰器处理。它在烧瓶内置网络服务器和Gunicorn中都能正常工作。该响应可以从装饰函数生成。在引入flask_restful之后,内置服务器正常工作,但在Gunicorn中,响应始终为{“message”:“Internal Server Error”}瓶子错误处理程序在引入flask_restful后不起作用gunicorn

这里是源代码:myapp.py在Gunicorn

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 -w4 -b0.0.0.0:8000 MYAPP:应用

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

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

在烧瓶内置服务器中运行时,问题不会发生。

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

+0

我的环境:瓶(0.10.1),瓶的RESTful(0.3.4),gunicorn(19.4.1) –

+0

这是因为它没有提高ORderNotExistError更可能。在500秒内添加一个错误处理程序,并查看响应是什么。 –

回答

0

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

要发现这个错误,您需要重写Werkzeug的例外,这是瓶颈安宁使用的例外。下面的代码应该修复它:

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