Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flask: wsgi-middleware vs before_ and after_request()

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

like image 280
bmaeser Avatar asked Aug 12 '12 23:08

bmaeser


1 Answers

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:

  1. If you are just writing a middleware that does something specific to your application, use the middleware of your framework.
  2. If you think your middleware is useful in a few of your apps, and might be helpful for other people, still use the middleware of your framework (what Flask would really typically call an "extension"). See Flask-SQLAlchemy as an example.
  3. If people are becoming really interested in your middleware, and are willing to help, think about converting it to an WSGI middleware library so that it can be used in other frameworks.
like image 154
Mark Hildreth Avatar answered Oct 19 '22 16:10

Mark Hildreth