.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
__init__.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2# pylint: disable=missing-module-docstring, too-few-public-methods
3
4import threading
5from copy import copy
6from timeit import default_timer
7from uuid import uuid4
8
9import flask
10from flask import copy_current_request_context
11import babel
12
13from searx import settings
14from searx.answerers import ask
15from searx.external_bang import get_bang_url
16from searx.results import ResultContainer
17from searx import logger
18from searx.plugins import plugins
19from searx.search.models import EngineRef, SearchQuery
20from searx.engines import load_engines
21from searx.network import initialize as initialize_network, check_network_configuration
22from searx.metrics import initialize as initialize_metrics, counter_inc, histogram_observe_time
23from searx.search.processors import PROCESSORS, initialize as initialize_processors
24from searx.search.checker import initialize as initialize_checker
25
26
27logger = logger.getChild('search')
28
29
30def initialize(settings_engines=None, enable_checker=False, check_network=False, enable_metrics=True):
31 settings_engines = settings_engines or settings['engines']
32 load_engines(settings_engines)
33 initialize_network(settings_engines, settings['outgoing'])
34 if check_network:
35 check_network_configuration()
36 initialize_metrics([engine['name'] for engine in settings_engines], enable_metrics)
37 initialize_processors(settings_engines)
38 if enable_checker:
39 initialize_checker()
40
41
42class Search:
43 """Search information container"""
44
45 __slots__ = "search_query", "result_container", "start_time", "actual_timeout"
46
47 def __init__(self, search_query: SearchQuery):
48 """Initialize the Search"""
49 # init vars
50 super().__init__()
51 self.search_query = search_query
52 self.result_container = ResultContainer()
53 self.start_time = None
54 self.actual_timeout = None
55
56 def search_external_bang(self):
57 """
58 Check if there is a external bang.
59 If yes, update self.result_container and return True
60 """
61 if self.search_query.external_bang:
62 self.result_container.redirect_url = get_bang_url(self.search_query)
63
64 # This means there was a valid bang and the
65 # rest of the search does not need to be continued
66 if isinstance(self.result_container.redirect_url, str):
67 return True
68 return False
69
70 def search_answerers(self):
71 """
72 Check if an answer return a result.
73 If yes, update self.result_container and return True
74 """
75 answerers_results = ask(self.search_query)
76
77 if answerers_results:
78 for results in answerers_results:
79 self.result_container.extend('answer', results)
80 return True
81 return False
82
83 # do search-request
84 def _get_requests(self):
85 # init vars
86 requests = []
87
88 # max of all selected engine timeout
89 default_timeout = 0
90
91 # start search-request for all selected engines
92 for engineref in self.search_query.engineref_list:
93 processor = PROCESSORS[engineref.name]
94
95 # stop the request now if the engine is suspend
96 if processor.extend_container_if_suspended(self.result_container):
97 continue
98
99 # set default request parameters
100 request_params = processor.get_params(self.search_query, engineref.category)
101 if request_params is None:
102 continue
103
104 counter_inc('engine', engineref.name, 'search', 'count', 'sent')
105
106 # append request to list
107 requests.append((engineref.name, self.search_query.query, request_params))
108
109 # update default_timeout
110 default_timeout = max(default_timeout, processor.engine.timeout)
111
112 # adjust timeout
113 max_request_timeout = settings['outgoing']['max_request_timeout']
114 actual_timeout = default_timeout
115 query_timeout = self.search_query.timeout_limit
116
117 if max_request_timeout is None and query_timeout is None:
118 # No max, no user query: default_timeout
119 pass
120 elif max_request_timeout is None and query_timeout is not None:
121 # No max, but user query: From user query except if above default
122 actual_timeout = min(default_timeout, query_timeout)
123 elif max_request_timeout is not None and query_timeout is None:
124 # Max, no user query: Default except if above max
125 actual_timeout = min(default_timeout, max_request_timeout)
126 elif max_request_timeout is not None and query_timeout is not None:
127 # Max & user query: From user query except if above max
128 actual_timeout = min(query_timeout, max_request_timeout)
129
130 logger.debug(
131 "actual_timeout={0} (default_timeout={1}, ?timeout_limit={2}, max_request_timeout={3})".format(
132 actual_timeout, default_timeout, query_timeout, max_request_timeout
133 )
134 )
135
136 return requests, actual_timeout
137
138 def search_multiple_requests(self, requests):
139 # pylint: disable=protected-access
140 search_id = str(uuid4())
141
142 for engine_name, query, request_params in requests:
143 _search = copy_current_request_context(PROCESSORS[engine_name].search)
144 th = threading.Thread( # pylint: disable=invalid-name
145 target=_search,
146 args=(query, request_params, self.result_container, self.start_time, self.actual_timeout),
147 name=search_id,
148 )
149 th._timeout = False
150 th._engine_name = engine_name
151 th.start()
152
153 for th in threading.enumerate(): # pylint: disable=invalid-name
154 if th.name == search_id:
155 remaining_time = max(0.0, self.actual_timeout - (default_timer() - self.start_time))
156 th.join(remaining_time)
157 if th.is_alive():
158 th._timeout = True
159 self.result_container.add_unresponsive_engine(th._engine_name, 'timeout')
160 PROCESSORS[th._engine_name].logger.error('engine timeout')
161
162 def search_standard(self):
163 """
164 Update self.result_container, self.actual_timeout
165 """
166 requests, self.actual_timeout = self._get_requests()
167
168 # send all search-request
169 if requests:
170 self.search_multiple_requests(requests)
171
172 # return results, suggestions, answers and infoboxes
173 return True
174
175 # do search-request
176 def search(self) -> ResultContainer:
177 self.start_time = default_timer()
178 if not self.search_external_bang():
179 if not self.search_answerers():
180 self.search_standard()
181 return self.result_container
182
183
184class SearchWithPlugins(Search):
185 """Inherit from the Search class, add calls to the plugins."""
186
187 __slots__ = 'ordered_plugin_list', 'request'
188
189 def __init__(self, search_query: SearchQuery, ordered_plugin_list, request: flask.Request):
190 super().__init__(search_query)
191 self.ordered_plugin_list = ordered_plugin_list
192 self.result_container.on_result = self._on_result
193 # pylint: disable=line-too-long
194 # get the "real" request to use it outside the Flask context.
195 # see
196 # * https://github.com/pallets/flask/blob/d01d26e5210e3ee4cbbdef12f05c886e08e92852/src/flask/globals.py#L55
197 # * https://github.com/pallets/werkzeug/blob/3c5d3c9bd0d9ce64590f0af8997a38f3823b368d/src/werkzeug/local.py#L548-L559
198 # * https://werkzeug.palletsprojects.com/en/2.0.x/local/#werkzeug.local.LocalProxy._get_current_object
199 # pylint: enable=line-too-long
200 self.request = request._get_current_object()
201
202 def _on_result(self, result):
203 return plugins.call(self.ordered_plugin_list, 'on_result', self.request, self, result)
204
205 def search(self) -> ResultContainer:
206 if plugins.call(self.ordered_plugin_list, 'pre_search', self.request, self):
207 super().search()
208
209 plugins.call(self.ordered_plugin_list, 'post_search', self.request, self)
210
211 self.result_container.close()
212
213 return self.result_container
::1337x
Definition 1337x.py:1
initialize(settings_engines=None, enable_checker=False, check_network=False, enable_metrics=True)
Definition __init__.py:30