2015-12-14 64 views
-1

我試圖通過顯式調用路由函數來執行一些測試。Flask中的請求上下文正確測試

from flask import Flask 
app = Flask(__name__) 


@app.route("/") 
def index(): 
    myfunc() 
    return "Index!" 

@app.route("/a") 
def hello(): 
    return "hello" 

def myfunc(): 
    with app.test_request_context('/', method='POST'): 
     app.hello() 


if __name__ == '__main__': 
    app.run(host='0.0.0.0', debug=True) 

但它失敗:

Traceback (most recent call last): 
    File "python2.7/site-packages/flask/app.py", line 1836, in __call__ 
    return self.wsgi_app(environ, start_response) 
    File "python2.7/site-packages/flask/app.py", line 1820, in wsgi_app 
    response = self.make_response(self.handle_exception(e)) 
    File "python2.7/site-packages/flask/app.py", line 1403, in handle_exception 
    reraise(exc_type, exc_value, tb) 
    File "python2.7/site-packages/flask/app.py", line 1817, in wsgi_app 
    response = self.full_dispatch_request() 
    File "python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request 
    rv = self.handle_user_exception(e) 
    File "python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception 
    reraise(exc_type, exc_value, tb) 
    File "python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request 
    rv = self.dispatch_request() 
    File "python2.7/site-packages/flask/app.py", line 1461, in dispatch_request 
    return self.view_functions[rule.endpoint](**req.view_args) 
    File "test.py", line 9, in index 
    myfunc() 
    File "test.py", line 18, in myfunc 
    app.hello() 
AttributeError: 'Flask' object has no attribute 'hello' 

是否有可能通過測試這種方式路由功能?

是的例子有點醜,但我需要弄清楚它有什麼問題。

回答

1

要進行「內部重定向」,或者從另一個視圖調用視圖,你把正確的URL和任何其他新的請求上下文所需數據,然後讓Flask調度請求。您可以在內部視圖中返回值,或者在外部視圖中返回您自己的響應。

from flask import Flask, request, url_for 

app = Flask(__name__) 

@app.route('/') 
def index(): 
    with app.test_request_context(
      url_for('hello'), 
      headers=request.headers.to_list(), 
      query_string=request.query_string 
    ): 
     return app.dispatch_request() 

@app.route('/greet') 
def hello(): 
    return 'Hello, {}!'.format(request.args.get('name', 'World')) 

app.run() 

導航到http://127.0.0.1/?name=davidism返回Hello, davidism!,從hello視圖的響應。


您不會通過像這樣的正在運行的應用程序調用視圖來測試視圖。要測試Flask應用程序,您可以使用單元測試和測試客戶端as described in the docs

with app.test_client() as c: 
    r = c.get('/a') 
    assert r.data.decode() == 'hello' 
+0

是否有可能通過這種方式調用'hello()',但從通常的(不是路由)函數? –

0

hello是一個常規函數,用app.route裝飾它不會將它添加到應用程序對象中。你或許意味着只是調用Hello功能,像這樣:

with ...: 
    hello() 
相關問題