.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
mysql_server.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""MySQL is said to be the most popular open source database. Before enabling
3MySQL engine, you must install the package ``mysql-connector-python``.
4
5The authentication plugin is configurable by setting ``auth_plugin`` in the
6attributes. By default it is set to ``caching_sha2_password``.
7
8Example
9=======
10
11This is an example configuration for querying a MySQL server:
12
13.. code:: yaml
14
15 - name: my_database
16 engine: mysql_server
17 database: my_database
18 username: searxng
19 password: password
20 limit: 5
21 query_str: 'SELECT * from my_table WHERE my_column=%(query)s'
22
23Implementations
24===============
25
26"""
27
28try:
29 import mysql.connector # type: ignore
30except ImportError:
31 # import error is ignored because the admin has to install mysql manually to use
32 # the engine
33 pass
34
35engine_type = 'offline'
36auth_plugin = 'caching_sha2_password'
37host = "127.0.0.1"
38port = 3306
39database = ""
40username = ""
41password = ""
42query_str = ""
43limit = 10
44paging = True
45result_template = 'key-value.html'
46_connection = None
47
48
49def init(engine_settings):
50 global _connection # pylint: disable=global-statement
51
52 if 'query_str' not in engine_settings:
53 raise ValueError('query_str cannot be empty')
54
55 if not engine_settings['query_str'].lower().startswith('select '):
56 raise ValueError('only SELECT query is supported')
57
58 _connection = mysql.connector.connect(
59 database=database,
60 user=username,
61 password=password,
62 host=host,
63 port=port,
64 auth_plugin=auth_plugin,
65 )
66
67
68def search(query, params):
69 query_params = {'query': query}
70 query_to_run = query_str + ' LIMIT {0} OFFSET {1}'.format(limit, (params['pageno'] - 1) * limit)
71
72 with _connection.cursor() as cur:
73 cur.execute(query_to_run, query_params)
74
75 return _fetch_results(cur)
76
77
79 results = []
80 for res in cur:
81 result = dict(zip(cur.column_names, map(str, res)))
82 result['template'] = result_template
83 results.append(result)
84
85 return results