1

app.handle_exceptionで例外が発生したときに呼び出されないように見えることに気付きましたapp.test_request_context:

from flask import *

app = Flask(__name__)
app.handle_exception = lambda e: 'exception!'

@app.route('/foo')
def foo():
    x = 1 / 0
    return 'ok'

if __name__ == '__main__':
    #app.run(port=81) # handle_exception works here
    with app.test_request_context('/foo'):
        print app.dispatch_request() # but not here

これは予想される動作ですか?

4

2 に答える 2

1

これがあなたが求めているものかどうかはわかりません: dispatch_request のドキュメントによると:

リクエストディスパッチを行います。URL に一致し、ビューまたはエラー ハンドラーの戻り値を返します。これは、応答オブジェクトである必要はありません。戻り値を適切な応答オブジェクトに変換するには、make_response() を呼び出します。

バージョン 0.7 で変更: これはもはや例外処理を行いません。このコードは新しい full_dispatch_request() に移動されました。

だから、おそらく交換...

with app.test_request_context('/foo'):
    print app.dispatch_request() # but not here

...と...

with app.test_request_context('/foo'):
    print app.full_dispatch_request() # Hopefully this works now :)
于 2013-03-29T15:28:50.683 に答える
1

この動作を簡単にオーバーライドして、同じハンドラーで例外処理を強制することができます。

def run_test(path=None,check_func=None,*args,**kwargs):
    with app.test_request_context(path,*args,**kwargs):
        try:
            data=app.dispatch_request() 
            if check_func is not None:
                 check_func()
            else:
                print data
        except Exception as e:
            print app.handle_exception(e)

run_test('/')
run_test('/other')

def current_test(data):
     assert 'has some content' in data
run_test('/should_be_checked',check_func=current_test)

そしてもう一言。

実際に例外をキャッチするFlaskのその部分を使用していないため、このアプローチは機能しません。コンテキストを直接呼び出しています。

ドキュメントからの引用:

Flask WSGI アプリケーションが内部でどのように機能するかを調べると、次のようなコードが見つかります。

def wsgi_app(self, environ):
    with self.request_context(environ):
        try:
            response = self.full_dispatch_request()
        except Exception, e:
            response = self.make_response(self.handle_exception(e))
        return response(environ, start_response)

しかし!すべてのレベルのすべての Flask メソッドが適切な方法で呼び出されるため、次の方法が正しい方法です。

with app.test_request_context():
    with app.test_client() as client:
        resp = client.get('/')
        #and if you need content of response: print resp.data

---

于 2013-03-29T14:16:55.653 に答える