mysql_server.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. # pylint: disable=missing-function-docstring
  4. """MySQL database (offline)
  5. """
  6. # import error is ignored because the admin has to install mysql manually to use
  7. # the engine
  8. import mysql.connector # pylint: disable=import-error
  9. engine_type = 'offline'
  10. auth_plugin = 'caching_sha2_password'
  11. host = "127.0.0.1"
  12. database = ""
  13. username = ""
  14. password = ""
  15. query_str = ""
  16. limit = 10
  17. paging = True
  18. result_template = 'key-value.html'
  19. _connection = None
  20. def init(engine_settings):
  21. global _connection # pylint: disable=global-statement
  22. if 'query_str' not in engine_settings:
  23. raise ValueError('query_str cannot be empty')
  24. if not engine_settings['query_str'].lower().startswith('select '):
  25. raise ValueError('only SELECT query is supported')
  26. _connection = mysql.connector.connect(
  27. database = database,
  28. user = username,
  29. password = password,
  30. host = host,
  31. auth_plugin=auth_plugin,
  32. )
  33. def search(query, params):
  34. query_params = {'query': query}
  35. query_to_run = query_str + ' LIMIT {0} OFFSET {1}'.format(limit, (params['pageno'] - 1) * limit)
  36. with _connection.cursor() as cur:
  37. cur.execute(query_to_run, query_params)
  38. return _fetch_results(cur)
  39. def _fetch_results(cur):
  40. results = []
  41. for res in cur:
  42. result = dict(zip(cur.column_names, map(str, res)))
  43. result['template'] = result_template
  44. results.append(result)
  45. return results