吞下Flask HTTPException

时间:2016-06-02 19:40:34

标签: python exception flask werkzeug

使用before_request声明函数时,Flask正在吞咽HTTPExceptions而不是传播它们:

from flask import Flask
from werkzeug.exceptions import HTTPException

app = Flask(__name__)

@app.before_request
def f():
    raise HTTPException("This is not propagated")

@app.route('/')
def test():
    return 'This is a view'


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

控制台显示没有异常:

$ python flask_test1.py
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [02/Jun/2016 15:01:31] "GET / HTTP/1.1" 200 -

浏览器显示:

Unknown Error

This is not propagated

有没有办法强迫它?我需要指定的设置,还是应该与Werkzeug HTTPExceptions接口并引发定制的异常?

1 个答案:

答案 0 :(得分:-1)

可能的原因是你不应该自己筹集HTTPException。对于其他异常,HTTPException本身应该是基类,例如BadRequestNotFound

由于HTTPException 没有要返回的HTTP代码,因此不会记录此类代码或将其发送给用户。如果你引发NotFoundBadRequest或HTTPException的任何子类,那些工作正常,至少在Flask 0.11中是这样的:

from werkzeug.exceptions import BadRequest
@app.before_request
def f():
    raise BadRequest("This is definitely propagated")