searchproviders.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from importlib import import_module
  2. from django.core.exceptions import PermissionDenied
  3. from misago.conf import settings
  4. class SearchProviders(object):
  5. def __init__(self, search_providers):
  6. self._initialized = False
  7. self._providers = []
  8. self.providers = search_providers
  9. def initialize_providers(self):
  10. if self._initialized:
  11. return
  12. self._initialized = True
  13. for modulename in self.providers:
  14. classname = modulename.split('.')[-1]
  15. module_path = '.'.join(modulename.split('.')[:-1])
  16. try:
  17. module = import_module(module_path)
  18. except ImportError:
  19. raise ImportError('search module %s could not be imported' % modulename)
  20. try:
  21. classdef = getattr(module, classname)
  22. self._providers.append(classdef)
  23. except AttributeError:
  24. raise ImportError('search module %s could not be imported' % modulename)
  25. def get_providers(self, request):
  26. if not self._initialized:
  27. self.initialize_providers()
  28. providers = []
  29. for provider in self._providers:
  30. providers.append(provider(request))
  31. return providers
  32. def get_allowed_providers(self, request):
  33. allowed_providers = []
  34. for provider in self.get_providers(request):
  35. try:
  36. provider.allow_search()
  37. allowed_providers.append(provider)
  38. except PermissionDenied:
  39. pass
  40. return allowed_providers
  41. searchproviders = SearchProviders(settings.MISAGO_SEARCH_EXTENSIONS)