flask: wsgi-middleware vs before_ and after_request() flask: wsgi-middleware vs before_ and after_request() flask flask

flask: wsgi-middleware vs before_ and after_request()


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.