2012-03-07 22:48:31 +00:00
|
|
|
"""Middleware used by django-watson."""
|
|
|
|
|
|
2013-05-02 14:50:16 +00:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
|
2015-11-09 09:52:36 +00:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2017-03-22 08:30:41 +00:00
|
|
|
try:
|
|
|
|
|
from django.utils.deprecation import MiddlewareMixin
|
|
|
|
|
cls = MiddlewareMixin
|
2017-11-27 08:54:17 +00:00
|
|
|
except ImportError:
|
2017-03-22 08:30:41 +00:00
|
|
|
cls = object
|
2015-11-09 09:52:36 +00:00
|
|
|
|
2015-12-02 10:39:36 +00:00
|
|
|
from watson.search import search_context_manager
|
2012-03-07 22:48:31 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
WATSON_MIDDLEWARE_FLAG = "watson.search_context_middleware_active"
|
|
|
|
|
|
|
|
|
|
|
2017-03-22 08:30:41 +00:00
|
|
|
class SearchContextMiddleware(cls):
|
2015-11-09 09:52:36 +00:00
|
|
|
|
2012-03-07 22:48:31 +00:00
|
|
|
"""Wraps the entire request in a search context."""
|
2015-11-09 09:52:36 +00:00
|
|
|
|
2012-03-07 22:48:31 +00:00
|
|
|
def process_request(self, request):
|
|
|
|
|
"""Starts a new search context."""
|
2015-11-09 09:52:36 +00:00
|
|
|
if request.META.get(WATSON_MIDDLEWARE_FLAG, False):
|
|
|
|
|
raise ImproperlyConfigured("SearchContextMiddleware can only be included in MIDDLEWARE_CLASSES once.")
|
|
|
|
|
request.META[WATSON_MIDDLEWARE_FLAG] = True
|
2012-03-07 22:48:31 +00:00
|
|
|
search_context_manager.start()
|
2015-11-09 09:52:36 +00:00
|
|
|
|
2012-03-07 22:48:31 +00:00
|
|
|
def _close_search_context(self, request):
|
|
|
|
|
"""Closes the search context."""
|
2015-11-09 09:52:36 +00:00
|
|
|
if request.META.get(WATSON_MIDDLEWARE_FLAG, False):
|
|
|
|
|
del request.META[WATSON_MIDDLEWARE_FLAG]
|
2012-03-07 22:48:31 +00:00
|
|
|
search_context_manager.end()
|
2015-11-09 09:52:36 +00:00
|
|
|
|
2012-03-07 22:48:31 +00:00
|
|
|
def process_response(self, request, response):
|
|
|
|
|
"""Closes the search context."""
|
|
|
|
|
self._close_search_context(request)
|
|
|
|
|
return response
|
2015-11-09 09:52:36 +00:00
|
|
|
|
2012-03-07 22:48:31 +00:00
|
|
|
def process_exception(self, request, exception):
|
|
|
|
|
"""Closes the search context."""
|
2015-11-09 09:52:36 +00:00
|
|
|
search_context_manager.invalidate()
|
2013-05-02 14:50:16 +00:00
|
|
|
self._close_search_context(request)
|