demo_offline.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Within this module we implement a *demo offline engine*. Do not look to
  3. close to the implementation, its just a simple example. To get in use of this
  4. *demo* engine add the following entry to your engines list in ``settings.yml``:
  5. .. code:: yaml
  6. - name: my offline engine
  7. engine: demo_offline
  8. shortcut: demo
  9. disabled: false
  10. """
  11. import json
  12. from searx.result_types import EngineResults
  13. from searx.enginelib import EngineCache
  14. engine_type = 'offline'
  15. categories = ['general']
  16. disabled = True
  17. timeout = 2.0
  18. about = {
  19. "wikidata_id": None,
  20. "official_api_documentation": None,
  21. "use_official_api": False,
  22. "require_api_key": False,
  23. "results": 'JSON',
  24. }
  25. # if there is a need for globals, use a leading underline
  26. _my_offline_engine: str = ""
  27. CACHE: EngineCache
  28. """Persistent (SQLite) key/value cache that deletes its values after ``expire``
  29. seconds."""
  30. def init(engine_settings):
  31. """Initialization of the (offline) engine. The origin of this demo engine is a
  32. simple json string which is loaded in this example while the engine is
  33. initialized."""
  34. global _my_offline_engine, CACHE # pylint: disable=global-statement
  35. CACHE = EngineCache(engine_settings["name"]) # type:ignore
  36. _my_offline_engine = (
  37. '[ {"value": "%s"}'
  38. ', {"value":"first item"}'
  39. ', {"value":"second item"}'
  40. ', {"value":"third item"}'
  41. ']' % engine_settings.get('name')
  42. )
  43. def search(query, request_params) -> EngineResults:
  44. """Query (offline) engine and return results. Assemble the list of results
  45. from your local engine. In this demo engine we ignore the 'query' term,
  46. usual you would pass the 'query' term to your local engine to filter out the
  47. results.
  48. """
  49. res = EngineResults()
  50. count = CACHE.get("count", 0)
  51. for row in json.loads(_my_offline_engine):
  52. count += 1
  53. kvmap = {
  54. 'query': query,
  55. 'language': request_params['searxng_locale'],
  56. 'value': row.get("value"),
  57. }
  58. res.add(
  59. res.types.KeyValue(
  60. caption=f"Demo Offline Engine Result #{count}",
  61. key_title="Name",
  62. value_title="Value",
  63. kvmap=kvmap,
  64. )
  65. )
  66. res.add(res.types.LegacyResult(number_of_results=count))
  67. # cache counter value for 20sec
  68. CACHE.set("count", count, expire=20)
  69. return res