【发布时间】:2019-11-27 13:42:17
【问题描述】:
我有一个 django 应用程序,它需要为相当多的功能设置一个会话,我不想再担心检查它是否在视图中设置,所以我将它移动到中间件,但是,我仍然有一个需要从中间件中排除的视图很少。
我决定装饰不需要中间件的特定视图,但我不确定如何检查装饰器是否存在。这可能吗?
到目前为止,我已尝试将其绑定到请求变量,但不起作用。
class CheckPropertyMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
@staticmethod
def process_view(request, view_func, args, kwargs):
print(request.property_not_important)
if not request.session.get('property'):
print('property not selected')
messages.error(request, 'You need to select a property to use the system.')
# return redirect(reverse('home', args=[request.client_url]))
else:
print('property selected')
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
return response
def property_not_important(function):
@functools.wraps(function)
def decorator(request, *args, **kwargs):
request.property_not_important = True
return function(request, *args, **kwargs)
return decorator
【问题讨论】:
标签: python django python-3.x python-decorators