I find it quite confusing what exactly are the differences in using Flask’s before_request() and/or after_request() versus using a WSGI middleware.
Say I want to do something very silly like this:
- Every request-body should be scanned for the word “bacon” and be replaced with “eggs”.
- Now request hits flask-view (according to url-mapping), view-function creates the response
- Every response-body should be scanned for “eggs” and replaced with “bacon”
Would I use a WSGI middleware or the Flask functions? Coming from django with a very robust middleware suite, the difference is not clear to me.
Thanks in advance.
berni
Actually, you have the exact same choice in Django. Django, in some part, is built on WSGI, so you could theoretically write WSGI middleware or Django middleware in Django as well. The reason you don’t have confusion there is because the Django community typically steers developers away from WSGI middleware. One reason is due to the fact that Django was designed to work equally on mod_python and WSGI. By using the Django middleware, your middleware works on both systems (see this post by James Bennett).
One advantage that creating a WSGI middleware has is that it can be used in multiple frameworks. For example, Beaker is a session and caching WSGI middleware that could be used in any WSGI framework. If it were written specifically in Flask, then Pyramid developers couldn’t use it. The maintainer of the library specifically made sure that the library could work in multiple frameworks, so he wrote it as a WSGI library.
Basically, this is how I would make my decision: