Are middlewares an implementation of the Decorator pattern?
Middlewares are not themselves decorators but it is possible to make decorators out of middlewares using a couple of built in functions in Django:
def decorator_from_middleware(middleware_class):
"""
Given a middleware class (not an instance), return a view decorator. This
lets you use middleware functionality on a per-view basis. The middleware
is created with no params passed.
"""
return make_middleware_decorator(middleware_class)()
def decorator_from_middleware_with_args(middleware_class):
"""
Like decorator_from_middleware, but return a function
that accepts the arguments to be passed to the middleware_class.
Use like::
cache_page = decorator_from_middleware_with_args(CacheMiddleware)
# ...
@cache_page(3600)
def my_view(request):
# ...
"""
return make_middleware_decorator(middleware_class)
Middleware and decorators are similar and can do the same job. They provide a means of inserting intermediary effects either before or after other effects downstream in the chain/stack.
A difference is that the middleware pipeline is computed using a reduction that presents the middleware with a simpler interface that hides the next middleware object in the chain. Rather it presents a next
function that applies the message to that object using the correct interface (e.g. IHandler.handle
).
Another difference is that it is easier to dynamically add/remove middleware because it exists in the middle of a container object (e.g. in an array) and the pipeline can be assembled on demand. A decorator is a stack of Russian dolls and its stack cannot so easily be rejiggered.