Flask app wrapped with DispatcherMiddleware no longer has test_client

送分小仙女□ 提交于 2019-12-07 04:12:55

问题


We can obtain test_client for sample application in way like:

class MyTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        my_app.app.config['TESTING'] = True
        cls.client = my_app.app.test_client()

However, if we wrap app with DispatcherMiddleware - we will get error like AttributeError: 'DispatcherMiddleware' object has no attribute 'test_client'.

Are there way to test composition of flask applications?

We want to be able to do something like:

cls.client = my_app.all_apps.test_client()

When all_apps is middleware like:

all_apps = DispatcherMiddleware(my_app, {
    '/backend': backend_app,
})

回答1:


To add WSGI middleware to a Flask app, wrap and replace the app's wsgi_app attribute. You're replacing the reference to the Flask app with a reference to some other WSGI app, which obviously won't have the same properties. By replacing wsgi_app, you retain the reference to the Flask app but change the WSGI callable that backs it.

app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {
    '/backend': backend_app
})



回答2:


I was looking to use the test_client on both of the bundled apps. Here is a modification to davidism's answer that allowed me to use test clients for both:

app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {
    '/backend': backend_app.wsgi_app
})


来源:https://stackoverflow.com/questions/36219842/flask-app-wrapped-with-dispatchermiddleware-no-longer-has-test-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!