我正在燒瓶中開發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.10.1),瓶的RESTful(0.3.4),gunicorn(19.4.1) –
這是因爲它沒有提高ORderNotExistError更可能。在500秒內添加一個錯誤處理程序,並查看響應是什麼。 –