2005-10-09 05:44:37 +08:00
|
|
|
"Functions that help with dynamically creating decorators for views."
|
|
|
|
|
|
|
|
def decorator_from_middleware(middleware_class):
|
|
|
|
"""
|
|
|
|
Given a middleware class (not an instance), returns a view decorator. This
|
|
|
|
lets you use middleware functionality on a per-view basis.
|
|
|
|
"""
|
|
|
|
def _decorator_from_middleware(view_func, *args, **kwargs):
|
|
|
|
middleware = middleware_class(*args, **kwargs)
|
|
|
|
def _wrapped_view(request, *args, **kwargs):
|
|
|
|
if hasattr(middleware, 'process_request'):
|
|
|
|
result = middleware.process_request(request)
|
|
|
|
if result is not None:
|
|
|
|
return result
|
2005-10-10 21:51:58 +08:00
|
|
|
if hasattr(middleware, 'process_view'):
|
2005-11-28 06:08:51 +08:00
|
|
|
result = middleware.process_view(request, view_func, *args, **kwargs)
|
2005-10-10 21:51:58 +08:00
|
|
|
if result is not None:
|
|
|
|
return result
|
2005-10-15 10:20:35 +08:00
|
|
|
try:
|
|
|
|
response = view_func(request, *args, **kwargs)
|
|
|
|
except Exception, e:
|
|
|
|
if hasattr(middleware, 'process_exception'):
|
|
|
|
result = middleware.process_exception(request, e)
|
|
|
|
if result is not None:
|
|
|
|
return result
|
2005-11-04 22:48:57 +08:00
|
|
|
raise
|
2005-10-09 05:44:37 +08:00
|
|
|
if hasattr(middleware, 'process_response'):
|
|
|
|
result = middleware.process_response(request, response)
|
|
|
|
if result is not None:
|
|
|
|
return result
|
|
|
|
return response
|
|
|
|
return _wrapped_view
|
|
|
|
return _decorator_from_middleware
|