__init__.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Implement request processors used by engine-types.
  3. """
  4. __all__ = [
  5. 'EngineProcessor',
  6. 'OfflineProcessor',
  7. 'OnlineProcessor',
  8. 'OnlineDictionaryProcessor',
  9. 'OnlineCurrencyProcessor',
  10. 'OnlineUrlSearchProcessor',
  11. 'PROCESSORS',
  12. ]
  13. import threading
  14. from typing import Dict
  15. from searx import logger
  16. from searx import engines
  17. from .online import OnlineProcessor
  18. from .offline import OfflineProcessor
  19. from .online_dictionary import OnlineDictionaryProcessor
  20. from .online_currency import OnlineCurrencyProcessor
  21. from .online_url_search import OnlineUrlSearchProcessor
  22. from .abstract import EngineProcessor
  23. logger = logger.getChild('search.processors')
  24. PROCESSORS: Dict[str, EngineProcessor] = {}
  25. """Cache request processors, stored by *engine-name* (:py:func:`initialize`)
  26. :meta hide-value:
  27. """
  28. def get_processor_class(engine_type):
  29. """Return processor class according to the ``engine_type``"""
  30. for c in [
  31. OnlineProcessor,
  32. OfflineProcessor,
  33. OnlineDictionaryProcessor,
  34. OnlineCurrencyProcessor,
  35. OnlineUrlSearchProcessor,
  36. ]:
  37. if c.engine_type == engine_type:
  38. return c
  39. return None
  40. def get_processor(engine, engine_name):
  41. """Return processor instance that fits to ``engine.engine.type``)"""
  42. engine_type = getattr(engine, 'engine_type', 'online')
  43. processor_class = get_processor_class(engine_type)
  44. if processor_class:
  45. return processor_class(engine, engine_name)
  46. return None
  47. def initialize_processor(processor):
  48. """Initialize one processor
  49. Call the init function of the engine
  50. """
  51. if processor.has_initialize_function:
  52. t = threading.Thread(target=processor.initialize, daemon=True)
  53. t.start()
  54. def initialize(engine_list):
  55. """Initialize all engines and store a processor for each engine in :py:obj:`PROCESSORS`."""
  56. for engine_data in engine_list:
  57. engine_name = engine_data['name']
  58. engine = engines.engines.get(engine_name)
  59. if engine:
  60. processor = get_processor(engine, engine_name)
  61. initialize_processor(processor)
  62. if processor is None:
  63. engine.logger.error('Error get processor for engine %s', engine_name)
  64. else:
  65. PROCESSORS[engine_name] = processor