我試圖通過顯式調用路由函數來執行一些測試。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'
是否有可能通過測試這種方式路由功能?
是的例子有點醜,但我需要弄清楚它有什麼問題。
是否有可能通過這種方式調用'hello()',但從通常的(不是路由)函數? –