mysql_server.py 1.4 KB

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