mysql_server.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. MySQL database (Offline)
  4. """
  5. # error is ignored because the admin has to
  6. # install it manually to use the engine
  7. # pylint: disable=import-error
  8. import mysql.connector
  9. engine_type = 'offline'
  10. auth_plugin = 'caching_sha2_password'
  11. host = "127.0.0.1"
  12. port = 3306
  13. database = ""
  14. username = ""
  15. password = ""
  16. query_str = ""
  17. limit = 10
  18. paging = True
  19. result_template = 'key-value.html'
  20. _connection = None
  21. def init(engine_settings):
  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. global _connection
  27. _connection = mysql.connector.connect(
  28. database=database,
  29. user=username,
  30. password=password,
  31. host=host,
  32. port=port,
  33. auth_plugin=auth_plugin,
  34. )
  35. def search(query, params):
  36. query_params = {'query': query}
  37. query_to_run = query_str + ' LIMIT {0} OFFSET {1}'.format(limit, (params['pageno'] - 1) * limit)
  38. with _connection.cursor() as cur:
  39. cur.execute(query_to_run, query_params)
  40. return _fetch_results(cur)
  41. def _fetch_results(cur):
  42. results = []
  43. for res in cur:
  44. result = dict(zip(cur.column_names, map(str, res)))
  45. result['template'] = result_template
  46. results.append(result)
  47. return results