在Django中,有中间件的概念。它包括更改请求并将其向下传递到下一个中间件,等等,然后对响应执行相反的操作。
中间件是设计模式装饰器的实现吗?他们是装饰者的一个特殊案例吗?它们之间有什么不同?
另外,Django中的装饰器的实现与GoF的描述有什么不同?
发布于 2019-10-26 10:45:47
中间件和装饰器是相似的,可以做同样的工作。它们提供了一种在链/堆栈下游的其他效果之前或之后插入中间效果的方法。
不同之处在于,中间件流水线是使用简化来计算的,该简化为中间件提供了隐藏链中下一个中间件对象的更简单的接口。相反,它提供了一个使用正确接口(例如IHandler.handle)将消息应用于该对象的next函数。
另一个不同之处是,动态添加/删除中间件更容易,因为它存在于容器对象的中间(例如,在数组中),并且管道可以按需组装。装饰者是一堆俄罗斯玩偶,它的堆叠不能那么容易地重新组合。
发布于 2018-02-09 08:15:42
中间件本身不是装饰器,但是可以使用Django中的几个built in functions从中间件中制作装饰器:
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)https://stackoverflow.com/questions/48696631
复制相似问题