on master help sign in
[mod] split searx.search into different processors

see searx.search.processors.abstract.EngineProcessor First the method searx call the get_params method. If the return value is not None, then the searx call the method search.

commit7ec8bc3ea76516e33318c67165161df5c1efdd36 authorAlexandre Flament <alex@al-f.net> dateWed 16 Dec 2020, 13:41 (6 years ago) parentc0cc01e
16 files changed+476−316
docs/admin/engines.rst+6−6 docs/dev/engine_overview.rst+1−1 searx/engines/__init__.py+6−4 searx/engines/command.py+1−1 searx/search/__init__.py+13−288 searx/search/processors/__init__.py+41 searx/search/processors/abstract.py+39 searx/search/processors/offline.py+51 searx/search/processors/online.py+211 searx/search/processors/online_currency.py+57 searx/search/processors/online_dictionary.py+37 searx/webapp.py+3−3 tests/unit/test_search.py+1−2 tests/unit/test_standalone_searx.py+2−3 tests/unit/test_webadapter.py+2−2 utils/standalone_searx.py+5−6
docs/admin/engines.rst+6−6
@@ -33,7 +33,7 @@ Engine .. Paging support **P**
3333------------------------- -------------------- ------------
3434Shortcut **S** Language support **L**
3535Timeout **TO** Time range support **TR**
36−Disabled **D** Offline **O**
36+Disabled **D** Engine type **ET**
3737------------- ----------- -------------------- ------------
3838Safe search **SS**
3939------------- ----------- ---------------------------------
@@ -62,10 +62,10 @@ Show errors **DE**
6262 - SS
6363 - D
6464 - TR
65− - O
66− - W
67− - D
68− - DE
65+ - ET
66+ - W
67+ - D
68+ - DE
6969
7070 {% for name, mod in engines.items() %}
7171
@@ -79,7 +79,7 @@ Show errors **DE**
7979 - {{(mod.safesearch and "y") or ""}}
8080 - {{(mod.disabled and "y") or ""}}
8181 - {{(mod.time_range_support and "y") or ""}}
82− - {{(mod.offline and "y") or ""}}
82+ - {{mod.engine_type or ""}}
8383 - {{mod.weight or 1 }}
8484 - {{(mod.disabled and "y") or ""}}
8585 - {{(mod.display_error_messages and "y") or ""}}
docs/dev/engine_overview.rst+1−1
@@ -44,7 +44,7 @@ categories list pages, in which the engine is working
4444paging boolean support multible pages
4545language_support boolean support language choosing
4646time_range_support boolean support search time range
47−offline boolean engine runs offline
47+engine_type str ``online`` by default, ``offline``
4848======================= =========== ===========================================
4949
5050.. _engine settings:
searx/engines/__init__.py+6−4
@@ -53,7 +53,7 @@ engine_default_args = {'paging': False,
5353 'suspend_end_time': 0,
5454 'continuous_errors': 0,
5555 'time_range_support': False,
56− 'offline': False,
56+ 'engine_type': 'online',
5757 'display_error_messages': True,
5858 'tokens': []}
5959
@@ -142,7 +142,9 @@ def load_engine(engine_data):
142142 'errors': 0
143143 }
144144
145− if not engine.offline:
145+ engine_type = getattr(engine, 'engine_type', 'online')
146+
147+ if engine_type != 'offline':
146148 engine.stats['page_load_time'] = 0
147149 engine.stats['page_load_count'] = 0
148150
@@ -209,7 +211,7 @@ def get_engines_stats(preferences):
209211 else:
210212 score = score_per_result = 0.0
211213
212− if not engine.offline:
214+ if engine.engine_type != 'offline':
213215 load_times = 0
214216 if engine.stats['page_load_count'] != 0:
215217 load_times = engine.stats['page_load_time'] / float(engine.stats['page_load_count']) # noqa
@@ -300,7 +302,7 @@ def initialize_engines(engine_list):
300302
301303def _set_https_support_for_engine(engine):
302304 # check HTTPS support if it is not disabled
303− if not engine.offline and not hasattr(engine, 'https_support'):
305+ if engine.engine_type != 'offline' and not hasattr(engine, 'https_support'):
304306 params = engine.request('http_test', {
305307 'method': 'GET',
306308 'headers': {},
searx/engines/command.py+1−1
@@ -23,7 +23,7 @@ from threading import Thread
2323from searx import logger
2424
2525
26−offline = True
26+engine_type = 'offline'
2727paging = True
2828command = []
2929delimiter = {}
searx/search/__init__.py+13−288
@@ -20,21 +20,15 @@ import gc
2020import threading
2121from time import time
2222from uuid import uuid4
23−from urllib.parse import urlparse
2423from _thread import start_new_thread
2524
26−import requests.exceptions
27−import searx.poolrequests as requests_lib
28−from searx.engines import engines, settings
25+from searx import settings
2926from searx.answerers import ask
3027from searx.external_bang import get_bang_url
31−from searx.utils import gen_useragent
3228from searx.results import ResultContainer
3329from searx import logger
3430from searx.plugins import plugins
35−from searx.exceptions import (SearxEngineAccessDeniedException, SearxEngineCaptchaException,
36− SearxEngineTooManyRequestsException,)
37−from searx.metrology.error_recorder import record_exception, record_error
31+from searx.search.processors import processors, initialize as initialize_processors
3832
3933
4034logger = logger.getChild('search')
@@ -51,6 +45,11 @@ else:
5145 sys.exit(1)
5246
5347
48+def initialize(settings_engines=None):
49+ settings_engines = settings_engines or settings['engines']
50+ initialize_processors(settings_engines)
51+
52+
5453class EngineRef:
5554
5655 __slots__ = 'name', 'category', 'from_bang'
@@ -110,231 +109,6 @@ class SearchQuery:
110109 and self.external_bang == other.external_bang
111110
112111
113−def send_http_request(engine, request_params):
114− # create dictionary which contain all
115− # informations about the request
116− request_args = dict(
117− headers=request_params['headers'],
118− cookies=request_params['cookies'],
119− verify=request_params['verify'],
120− auth=request_params['auth']
121− )
122−
123− # setting engine based proxies
124− if hasattr(engine, 'proxies'):
125− request_args['proxies'] = requests_lib.get_proxies(engine.proxies)
126−
127− # max_redirects
128− max_redirects = request_params.get('max_redirects')
129− if max_redirects:
130− request_args['max_redirects'] = max_redirects
131−
132− # soft_max_redirects
133− soft_max_redirects = request_params.get('soft_max_redirects', max_redirects or 0)
134−
135− # raise_for_status
136− request_args['raise_for_httperror'] = request_params.get('raise_for_httperror', False)
137−
138− # specific type of request (GET or POST)
139− if request_params['method'] == 'GET':
140− req = requests_lib.get
141− else:
142− req = requests_lib.post
143−
144− request_args['data'] = request_params['data']
145−
146− # send the request
147− response = req(request_params['url'], **request_args)
148−
149− # check soft limit of the redirect count
150− if len(response.history) > soft_max_redirects:
151− # unexpected redirect : record an error
152− # but the engine might still return valid results.
153− status_code = str(response.status_code or '')
154− reason = response.reason or ''
155− hostname = str(urlparse(response.url or '').netloc)
156− record_error(engine.name,
157− '{} redirects, maximum: {}'.format(len(response.history), soft_max_redirects),
158− (status_code, reason, hostname))
159−
160− return response
161−
162−
163−def search_one_http_request(engine, query, request_params):
164− # update request parameters dependent on
165− # search-engine (contained in engines folder)
166− engine.request(query, request_params)
167−
168− # ignoring empty urls
169− if request_params['url'] is None:
170− return None
171−
172− if not request_params['url']:
173− return None
174−
175− # send request
176− response = send_http_request(engine, request_params)
177−
178− # parse the response
179− response.search_params = request_params
180− return engine.response(response)
181−
182−
183−def search_one_http_request_safe(engine_name, query, request_params, result_container, start_time, timeout_limit):
184− # set timeout for all HTTP requests
185− requests_lib.set_timeout_for_thread(timeout_limit, start_time=start_time)
186− # reset the HTTP total time
187− requests_lib.reset_time_for_thread()
188−
189− #
190− engine = engines[engine_name]
191−
192− # suppose everything will be alright
193− requests_exception = False
194− suspended_time = None
195−
196− try:
197− # send requests and parse the results
198− search_results = search_one_http_request(engine, query, request_params)
199−
200− # check if the engine accepted the request
201− if search_results is not None:
202− # yes, so add results
203− result_container.extend(engine_name, search_results)
204−
205− # update engine time when there is no exception
206− engine_time = time() - start_time
207− page_load_time = requests_lib.get_time_for_thread()
208− result_container.add_timing(engine_name, engine_time, page_load_time)
209− with threading.RLock():
210− engine.stats['engine_time'] += engine_time
211− engine.stats['engine_time_count'] += 1
212− # update stats with the total HTTP time
213− engine.stats['page_load_time'] += page_load_time
214− engine.stats['page_load_count'] += 1
215− except Exception as e:
216− record_exception(engine_name, e)
217−
218− # Timing
219− engine_time = time() - start_time
220− page_load_time = requests_lib.get_time_for_thread()
221− result_container.add_timing(engine_name, engine_time, page_load_time)
222−
223− # Record the errors
224− with threading.RLock():
225− engine.stats['errors'] += 1
226−
227− if (issubclass(e.__class__, requests.exceptions.Timeout)):
228− result_container.add_unresponsive_engine(engine_name, 'HTTP timeout')
229− # requests timeout (connect or read)
230− logger.error("engine {0} : HTTP requests timeout"
231− "(search duration : {1} s, timeout: {2} s) : {3}"
232− .format(engine_name, engine_time, timeout_limit, e.__class__.__name__))
233− requests_exception = True
234− elif (issubclass(e.__class__, requests.exceptions.RequestException)):
235− result_container.add_unresponsive_engine(engine_name, 'HTTP error')
236− # other requests exception
237− logger.exception("engine {0} : requests exception"
238− "(search duration : {1} s, timeout: {2} s) : {3}"
239− .format(engine_name, engine_time, timeout_limit, e))
240− requests_exception = True
241− elif (issubclass(e.__class__, SearxEngineCaptchaException)):
242− result_container.add_unresponsive_engine(engine_name, 'CAPTCHA required')
243− logger.exception('engine {0} : CAPTCHA')
244− suspended_time = e.suspended_time # pylint: disable=no-member
245− elif (issubclass(e.__class__, SearxEngineTooManyRequestsException)):
246− result_container.add_unresponsive_engine(engine_name, 'too many requests')
247− logger.exception('engine {0} : Too many requests')
248− suspended_time = e.suspended_time # pylint: disable=no-member
249− elif (issubclass(e.__class__, SearxEngineAccessDeniedException)):
250− result_container.add_unresponsive_engine(engine_name, 'blocked')
251− logger.exception('engine {0} : Searx is blocked')
252− suspended_time = e.suspended_time # pylint: disable=no-member
253− else:
254− result_container.add_unresponsive_engine(engine_name, 'unexpected crash')
255− # others errors
256− logger.exception('engine {0} : exception : {1}'.format(engine_name, e))
257− else:
258− if getattr(threading.current_thread(), '_timeout', False):
259− record_error(engine_name, 'Timeout')
260−
261− # suspend the engine if there is an HTTP error
262− # or suspended_time is defined
263− with threading.RLock():
264− if requests_exception or suspended_time:
265− # update continuous_errors / suspend_end_time
266− engine.continuous_errors += 1
267− if suspended_time is None:
268− suspended_time = min(settings['search']['max_ban_time_on_fail'],
269− engine.continuous_errors * settings['search']['ban_time_on_fail'])
270− engine.suspend_end_time = time() + suspended_time
271− else:
272− # reset the suspend variables
273− engine.continuous_errors = 0
274− engine.suspend_end_time = 0
275−
276−
277−def record_offline_engine_stats_on_error(engine, result_container, start_time):
278− engine_time = time() - start_time
279− result_container.add_timing(engine.name, engine_time, engine_time)
280−
281− with threading.RLock():
282− engine.stats['errors'] += 1
283−
284−
285−def search_one_offline_request(engine, query, request_params):
286− return engine.search(query, request_params)
287−
288−
289−def search_one_offline_request_safe(engine_name, query, request_params, result_container, start_time, timeout_limit):
290− engine = engines[engine_name]
291−
292− try:
293− search_results = search_one_offline_request(engine, query, request_params)
294−
295− if search_results:
296− result_container.extend(engine_name, search_results)
297−
298− engine_time = time() - start_time
299− result_container.add_timing(engine_name, engine_time, engine_time)
300− with threading.RLock():
301− engine.stats['engine_time'] += engine_time
302− engine.stats['engine_time_count'] += 1
303−
304− except ValueError as e:
305− record_exception(engine_name, e)
306− record_offline_engine_stats_on_error(engine, result_container, start_time)
307− logger.exception('engine {0} : invalid input : {1}'.format(engine_name, e))
308− except Exception as e:
309− record_exception(engine_name, e)
310− record_offline_engine_stats_on_error(engine, result_container, start_time)
311− result_container.add_unresponsive_engine(engine_name, 'unexpected crash', str(e))
312− logger.exception('engine {0} : exception : {1}'.format(engine_name, e))
313− else:
314− if getattr(threading.current_thread(), '_timeout', False):
315− record_error(engine_name, 'Timeout')
316−
317−
318−def search_one_request_safe(engine_name, query, request_params, result_container, start_time, timeout_limit):
319− if engines[engine_name].offline:
320− return search_one_offline_request_safe(engine_name, query, request_params, result_container, start_time, timeout_limit) # noqa
321− return search_one_http_request_safe(engine_name, query, request_params, result_container, start_time, timeout_limit)
322−
323−
324−# get default reqest parameter
325−def default_request_params():
326− return {
327− 'method': 'GET',
328− 'headers': {},
329− 'data': {},
330− 'url': '',
331− 'cookies': {},
332− 'verify': True,
333− 'auth': None,
334− 'raise_for_httperror': True
335− }
336−
337−
338112class Search:
339113 """Search information container"""
340114
@@ -375,69 +149,20 @@ class Search:
375149 return True
376150 return False
377151
378− def _is_accepted(self, engine_name, engine):
379− # skip suspended engines
380− if engine.suspend_end_time >= time():
381− logger.debug('Engine currently suspended: %s', engine_name)
382− return False
383−
384− # if paging is not supported, skip
385− if self.search_query.pageno > 1 and not engine.paging:
386− return False
387−
388− # if time_range is not supported, skip
389− if self.search_query.time_range and not engine.time_range_support:
390− return False
391−
392− return True
393−
394− def _get_params(self, engineref, user_agent):
395− if engineref.name not in engines:
396− return None, None
397−
398− engine = engines[engineref.name]
399−
400− if not self._is_accepted(engineref.name, engine):
401− return None, None
402−
403− # set default request parameters
404− request_params = {}
405− if not engine.offline:
406− request_params = default_request_params()
407− request_params['headers']['User-Agent'] = user_agent
408−
409− if hasattr(engine, 'language') and engine.language:
410− request_params['language'] = engine.language
411− else:
412− request_params['language'] = self.search_query.lang
413−
414− request_params['safesearch'] = self.search_query.safesearch
415− request_params['time_range'] = self.search_query.time_range
416−
417− request_params['category'] = engineref.category
418− request_params['pageno'] = self.search_query.pageno
419−
420− with threading.RLock():
421− engine.stats['sent_search_count'] += 1
422−
423− return request_params, engine.timeout
424−
425152 # do search-request
426153 def _get_requests(self):
427154 # init vars
428155 requests = []
429156
430− # set default useragent
431− # user_agent = request.headers.get('User-Agent', '')
432− user_agent = gen_useragent()
433−
434157 # max of all selected engine timeout
435158 default_timeout = 0
436159
437160 # start search-reqest for all selected engines
438161 for engineref in self.search_query.engineref_list:
162+ processor = processors[engineref.name]
163+
439164 # set default request parameters
440− request_params, engine_timeout = self._get_params(engineref, user_agent)
165+ request_params = processor.get_params(self.search_query, engineref.category)
441166 if request_params is None:
442167 continue
443168
@@ -445,7 +170,7 @@ class Search:
445170 requests.append((engineref.name, self.search_query.query, request_params))
446171
447172 # update default_timeout
448− default_timeout = max(default_timeout, engine_timeout)
173+ default_timeout = max(default_timeout, processor.engine.timeout)
449174
450175 # adjust timeout
451176 actual_timeout = default_timeout
@@ -474,8 +199,8 @@ class Search:
474199
475200 for engine_name, query, request_params in requests:
476201 th = threading.Thread(
477− target=search_one_request_safe,
478− args=(engine_name, query, request_params, self.result_container, self.start_time, self.actual_timeout),
202+ target=processors[engine_name].search,
203+ args=(query, request_params, self.result_container, self.start_time, self.actual_timeout),
479204 name=search_id,
480205 )
481206 th._timeout = False
searx/search/processors/__init__.pynew file+41
@@ -0,0 +1,41 @@
1+# SPDX-License-Identifier: AGPL-3.0-or-later
2+
3+from .online import OnlineProcessor
4+from .offline import OfflineProcessor
5+from .online_dictionary import OnlineDictionaryProcessor
6+from .online_currency import OnlineCurrencyProcessor
7+from .abstract import EngineProcessor
8+from searx import logger
9+import searx.engines as engines
10+
11+
12+__all__ = ['EngineProcessor', 'OfflineProcessor', 'OnlineProcessor',
13+ 'OnlineDictionaryProcessor', 'OnlineCurrencyProcessor', 'processors']
14+logger = logger.getChild('search.processors')
15+processors = {}
16+
17+
18+def get_processor_class(engine_type):
19+ for c in [OnlineProcessor, OfflineProcessor, OnlineDictionaryProcessor, OnlineCurrencyProcessor]:
20+ if c.engine_type == engine_type:
21+ return c
22+ return None
23+
24+
25+def get_processor(engine, engine_name):
26+ engine_type = getattr(engine, 'engine_type', 'online')
27+ processor_class = get_processor_class(engine_type)
28+ if processor_class:
29+ return processor_class(engine, engine_name)
30+ else:
31+ return None
32+
33+
34+def initialize(engine_list):
35+ engines.initialize_engines(engine_list)
36+ for engine_name, engine in engines.engines.items():
37+ processor = get_processor(engine, engine_name)
38+ if processor is None:
39+ logger.error('Error get processor for engine %s', engine_name)
40+ else:
41+ processors[engine_name] = processor
searx/search/processors/abstract.pynew file+39
@@ -0,0 +1,39 @@
1+# SPDX-License-Identifier: AGPL-3.0-or-later
2+
3+from abc import abstractmethod
4+from searx import logger
5+
6+
7+logger = logger.getChild('searx.search.processor')
8+
9+
10+class EngineProcessor:
11+
12+ def __init__(self, engine, engine_name):
13+ self.engine = engine
14+ self.engine_name = engine_name
15+
16+ def get_params(self, search_query, engine_category):
17+ # if paging is not supported, skip
18+ if search_query.pageno > 1 and not self.engine.paging:
19+ return None
20+
21+ # if time_range is not supported, skip
22+ if search_query.time_range and not self.engine.time_range_support:
23+ return None
24+
25+ params = {}
26+ params['category'] = engine_category
27+ params['pageno'] = search_query.pageno
28+ params['safesearch'] = search_query.safesearch
29+ params['time_range'] = search_query.time_range
30+
31+ if hasattr(self.engine, 'language') and self.engine.language:
32+ params['language'] = self.engine.language
33+ else:
34+ params['language'] = search_query.lang
35+ return params
36+
37+ @abstractmethod
38+ def search(self, query, params, result_container, start_time, timeout_limit):
39+ pass
searx/search/processors/offline.pynew file+51
@@ -0,0 +1,51 @@
1+# SPDX-License-Identifier: AGPL-3.0-or-later
2+
3+import threading
4+from time import time
5+from searx import logger
6+from searx.metrology.error_recorder import record_exception, record_error
7+from searx.search.processors.abstract import EngineProcessor
8+
9+
10+logger = logger.getChild('search.processor.offline')
11+
12+
13+class OfflineProcessor(EngineProcessor):
14+
15+ engine_type = 'offline'
16+
17+ def _record_stats_on_error(self, result_container, start_time):
18+ engine_time = time() - start_time
19+ result_container.add_timing(self.engine_name, engine_time, engine_time)
20+
21+ with threading.RLock():
22+ self.engine.stats['errors'] += 1
23+
24+ def _search_basic(self, query, params):
25+ return self.engine.search(query, params)
26+
27+ def search(self, query, params, result_container, start_time, timeout_limit):
28+ try:
29+ search_results = self._search_basic(query, params)
30+
31+ if search_results:
32+ result_container.extend(self.engine_name, search_results)
33+
34+ engine_time = time() - start_time
35+ result_container.add_timing(self.engine_name, engine_time, engine_time)
36+ with threading.RLock():
37+ self.engine.stats['engine_time'] += engine_time
38+ self.engine.stats['engine_time_count'] += 1
39+
40+ except ValueError as e:
41+ record_exception(self.engine_name, e)
42+ self._record_stats_on_error(result_container, start_time)
43+ logger.exception('engine {0} : invalid input : {1}'.format(self.engine_name, e))
44+ except Exception as e:
45+ record_exception(self.engine_name, e)
46+ self._record_stats_on_error(result_container, start_time)
47+ result_container.add_unresponsive_engine(self.engine_name, 'unexpected crash', str(e))
48+ logger.exception('engine {0} : exception : {1}'.format(self.engine_name, e))
49+ else:
50+ if getattr(threading.current_thread(), '_timeout', False):
51+ record_error(self.engine_name, 'Timeout')
searx/search/processors/online.pynew file+211
@@ -0,0 +1,211 @@
1+# SPDX-License-Identifier: AGPL-3.0-or-later
2+
3+from urllib.parse import urlparse
4+from time import time
5+import threading
6+
7+import requests.exceptions
8+
9+import searx.poolrequests as poolrequests
10+from searx.engines import settings
11+from searx import logger
12+from searx.utils import gen_useragent
13+from searx.exceptions import (SearxEngineAccessDeniedException, SearxEngineCaptchaException,
14+ SearxEngineTooManyRequestsException,)
15+from searx.metrology.error_recorder import record_exception, record_error
16+
17+from searx.search.processors.abstract import EngineProcessor
18+
19+
20+logger = logger.getChild('search.processor.online')
21+
22+DEFAULT_PARAMS = {
23+ 'method': 'GET',
24+ 'headers': {},
25+ 'data': {},
26+ 'url': '',
27+ 'cookies': {},
28+ 'verify': True,
29+ 'auth': None
30+}
31+
32+
33+class OnlineProcessor(EngineProcessor):
34+
35+ engine_type = 'online'
36+
37+ def get_params(self, search_query, engine_category):
38+ params = super().get_params(search_query, engine_category)
39+ if params is None:
40+ return None
41+
42+ # skip suspended engines
43+ if self.engine.suspend_end_time >= time():
44+ logger.debug('Engine currently suspended: %s', self.engine_name)
45+ return None
46+
47+ # add default params
48+ params.update(DEFAULT_PARAMS)
49+
50+ # add an user agent
51+ params['headers']['User-Agent'] = gen_useragent()
52+
53+ return params
54+
55+ def _send_http_request(self, params):
56+ # create dictionary which contain all
57+ # informations about the request
58+ request_args = dict(
59+ headers=params['headers'],
60+ cookies=params['cookies'],
61+ verify=params['verify'],
62+ auth=params['auth']
63+ )
64+
65+ # setting engine based proxies
66+ if hasattr(self.engine, 'proxies'):
67+ request_args['proxies'] = poolrequests.get_proxies(self.engine.proxies)
68+
69+ # max_redirects
70+ max_redirects = params.get('max_redirects')
71+ if max_redirects:
72+ request_args['max_redirects'] = max_redirects
73+
74+ # soft_max_redirects
75+ soft_max_redirects = params.get('soft_max_redirects', max_redirects or 0)
76+
77+ # raise_for_status
78+ request_args['raise_for_httperror'] = params.get('raise_for_httperror', False)
79+
80+ # specific type of request (GET or POST)
81+ if params['method'] == 'GET':
82+ req = poolrequests.get
83+ else:
84+ req = poolrequests.post
85+
86+ request_args['data'] = params['data']
87+
88+ # send the request
89+ response = req(params['url'], **request_args)
90+
91+ # check soft limit of the redirect count
92+ if len(response.history) > soft_max_redirects:
93+ # unexpected redirect : record an error
94+ # but the engine might still return valid results.
95+ status_code = str(response.status_code or '')
96+ reason = response.reason or ''
97+ hostname = str(urlparse(response.url or '').netloc)
98+ record_error(self.engine_name,
99+ '{} redirects, maximum: {}'.format(len(response.history), soft_max_redirects),
100+ (status_code, reason, hostname))
101+
102+ return response
103+
104+ def _search_basic(self, query, params):
105+ # update request parameters dependent on
106+ # search-engine (contained in engines folder)
107+ self.engine.request(query, params)
108+
109+ # ignoring empty urls
110+ if params['url'] is None:
111+ return None
112+
113+ if not params['url']:
114+ return None
115+
116+ # send request
117+ response = self._send_http_request(params)
118+
119+ # parse the response
120+ response.search_params = params
121+ return self.engine.response(response)
122+
123+ def search(self, query, params, result_container, start_time, timeout_limit):
124+ # set timeout for all HTTP requests
125+ poolrequests.set_timeout_for_thread(timeout_limit, start_time=start_time)
126+ # reset the HTTP total time
127+ poolrequests.reset_time_for_thread()
128+
129+ # suppose everything will be alright
130+ requests_exception = False
131+ suspended_time = None
132+
133+ try:
134+ # send requests and parse the results
135+ search_results = self._search_basic(query, params)
136+
137+ # check if the engine accepted the request
138+ if search_results is not None:
139+ # yes, so add results
140+ result_container.extend(self.engine_name, search_results)
141+
142+ # update engine time when there is no exception
143+ engine_time = time() - start_time
144+ page_load_time = poolrequests.get_time_for_thread()
145+ result_container.add_timing(self.engine_name, engine_time, page_load_time)
146+ with threading.RLock():
147+ self.engine.stats['engine_time'] += engine_time
148+ self.engine.stats['engine_time_count'] += 1
149+ # update stats with the total HTTP time
150+ self.engine.stats['page_load_time'] += page_load_time
151+ self.engine.stats['page_load_count'] += 1
152+ except Exception as e:
153+ record_exception(self.engine_name, e)
154+
155+ # Timing
156+ engine_time = time() - start_time
157+ page_load_time = poolrequests.get_time_for_thread()
158+ result_container.add_timing(self.engine_name, engine_time, page_load_time)
159+
160+ # Record the errors
161+ with threading.RLock():
162+ self.engine.stats['errors'] += 1
163+
164+ if (issubclass(e.__class__, requests.exceptions.Timeout)):
165+ result_container.add_unresponsive_engine(self.engine_name, 'HTTP timeout')
166+ # requests timeout (connect or read)
167+ logger.error("engine {0} : HTTP requests timeout"
168+ "(search duration : {1} s, timeout: {2} s) : {3}"
169+ .format(self.engine_name, engine_time, timeout_limit, e.__class__.__name__))
170+ requests_exception = True
171+ elif (issubclass(e.__class__, requests.exceptions.RequestException)):
172+ result_container.add_unresponsive_engine(self.engine_name, 'HTTP error')
173+ # other requests exception
174+ logger.exception("engine {0} : requests exception"
175+ "(search duration : {1} s, timeout: {2} s) : {3}"
176+ .format(self.engine_name, engine_time, timeout_limit, e))
177+ requests_exception = True
178+ elif (issubclass(e.__class__, SearxEngineCaptchaException)):
179+ result_container.add_unresponsive_engine(self.engine_name, 'CAPTCHA required')
180+ logger.exception('engine {0} : CAPTCHA')
181+ suspended_time = e.suspended_time # pylint: disable=no-member
182+ elif (issubclass(e.__class__, SearxEngineTooManyRequestsException)):
183+ result_container.add_unresponsive_engine(self.engine_name, 'too many requests')
184+ logger.exception('engine {0} : Too many requests')
185+ suspended_time = e.suspended_time # pylint: disable=no-member
186+ elif (issubclass(e.__class__, SearxEngineAccessDeniedException)):
187+ result_container.add_unresponsive_engine(self.engine_name, 'blocked')
188+ logger.exception('engine {0} : Searx is blocked')
189+ suspended_time = e.suspended_time # pylint: disable=no-member
190+ else:
191+ result_container.add_unresponsive_engine(self.engine_name, 'unexpected crash')
192+ # others errors
193+ logger.exception('engine {0} : exception : {1}'.format(self.engine_name, e))
194+ else:
195+ if getattr(threading.current_thread(), '_timeout', False):
196+ record_error(self.engine_name, 'Timeout')
197+
198+ # suspend the engine if there is an HTTP error
199+ # or suspended_time is defined
200+ with threading.RLock():
201+ if requests_exception or suspended_time:
202+ # update continuous_errors / suspend_end_time
203+ self.engine.continuous_errors += 1
204+ if suspended_time is None:
205+ suspended_time = min(settings['search']['max_ban_time_on_fail'],
206+ self.engine.continuous_errors * settings['search']['ban_time_on_fail'])
207+ self.engine.suspend_end_time = time() + suspended_time
208+ else:
209+ # reset the suspend variables
210+ self.engine.continuous_errors = 0
211+ self.engine.suspend_end_time = 0
searx/search/processors/online_currency.pynew file+57
@@ -0,0 +1,57 @@
1+# SPDX-License-Identifier: AGPL-3.0-or-later
2+
3+import unicodedata
4+import re
5+
6+from searx.data import CURRENCIES
7+from .online import OnlineProcessor
8+
9+
10+parser_re = re.compile('.*?(\\d+(?:\\.\\d+)?) ([^.0-9]+) (?:in|to) ([^.0-9]+)', re.I)
11+
12+
13+def normalize_name(name):
14+ name = name.lower().replace('-', ' ').rstrip('s')
15+ name = re.sub(' +', ' ', name)
16+ return unicodedata.normalize('NFKD', name).lower()
17+
18+
19+def name_to_iso4217(name):
20+ global CURRENCIES
21+ name = normalize_name(name)
22+ currency = CURRENCIES['names'].get(name, [name])
23+ return currency[0]
24+
25+
26+def iso4217_to_name(iso4217, language):
27+ global CURRENCIES
28+ return CURRENCIES['iso4217'].get(iso4217, {}).get(language, iso4217)
29+
30+
31+class OnlineCurrencyProcessor(OnlineProcessor):
32+
33+ engine_type = 'online_currency'
34+
35+ def get_params(self, search_query, engine_category):
36+ params = super().get_params(search_query, engine_category)
37+ if params is None:
38+ return None
39+
40+ m = parser_re.match(search_query.query)
41+ if not m:
42+ return None
43+
44+ amount_str, from_currency, to_currency = m.groups()
45+ try:
46+ amount = float(amount_str)
47+ except ValueError:
48+ return None
49+ from_currency = name_to_iso4217(from_currency.strip())
50+ to_currency = name_to_iso4217(to_currency.strip())
51+
52+ params['amount'] = amount
53+ params['from'] = from_currency
54+ params['to'] = to_currency
55+ params['from_name'] = iso4217_to_name(from_currency, 'en')
56+ params['to_name'] = iso4217_to_name(to_currency, 'en')
57+ return params
searx/search/processors/online_dictionary.pynew file+37
@@ -0,0 +1,37 @@
1+# SPDX-License-Identifier: AGPL-3.0-or-later
2+
3+import re
4+
5+from searx.utils import is_valid_lang
6+from .online import OnlineProcessor
7+
8+
9+parser_re = re.compile('.*?([a-z]+)-([a-z]+) ([^ ]+)$', re.I)
10+
11+
12+class OnlineDictionaryProcessor(OnlineProcessor):
13+
14+ engine_type = 'online_dictionnary'
15+
16+ def get_params(self, search_query, engine_category):
17+ params = super().get_params(search_query, engine_category)
18+ if params is None:
19+ return None
20+
21+ m = parser_re.match(search_query.query)
22+ if not m:
23+ return None
24+
25+ from_lang, to_lang, query = m.groups()
26+
27+ from_lang = is_valid_lang(from_lang)
28+ to_lang = is_valid_lang(to_lang)
29+
30+ if not from_lang or not to_lang:
31+ return None
32+
33+ params['from_lang'] = from_lang
34+ params['to_lang'] = to_lang
35+ params['query'] = query
36+
37+ return params
searx/webapp.py+3−3
@@ -60,7 +60,7 @@ from searx import brand, static_path
6060from searx import settings, searx_dir, searx_debug
6161from searx.exceptions import SearxParameterException
6262from searx.engines import (
63− categories, engines, engine_shortcuts, get_engines_stats, initialize_engines
63+ categories, engines, engine_shortcuts, get_engines_stats
6464)
6565from searx.webutils import (
6666 UnicodeWriter, highlight_content, get_resources_directory,
@@ -71,7 +71,7 @@ from searx.webadapter import get_search_query_from_webapp, get_selected_categori
7171from searx.utils import html_to_text, gen_useragent, dict_subset, match_language
7272from searx.version import VERSION_STRING
7373from searx.languages import language_codes as languages
74−from searx.search import SearchWithPlugins
74+from searx.search import SearchWithPlugins, initialize
7575from searx.query import RawTextQuery
7676from searx.autocomplete import searx_bang, backends as autocomplete_backends
7777from searx.plugins import plugins
@@ -131,7 +131,7 @@ werkzeug_reloader = flask_run_development or (searx_debug and __name__ == "__mai
131131# initialize the engines except on the first run of the werkzeug server.
132132if not werkzeug_reloader\
133133 or (werkzeug_reloader and os.environ.get("WERKZEUG_RUN_MAIN") == "true"):
134− initialize_engines(settings['engines'])
134+ initialize()
135135
136136babel = Babel(app)
137137
tests/unit/test_search.py+1−2
@@ -3,7 +3,6 @@
33from searx.testing import SearxTestCase
44from searx.search import SearchQuery, EngineRef
55import searx.search
6−import searx.engines
76
87
98SAFESEARCH = 0
@@ -39,7 +38,7 @@ class SearchTestCase(SearxTestCase):
3938
4039 @classmethod
4140 def setUpClass(cls):
42− searx.engines.initialize_engines(TEST_ENGINES)
41+ searx.search.initialize(TEST_ENGINES)
4342
4443 def test_timeout_simple(self):
4544 searx.search.max_request_timeout = None
tests/unit/test_standalone_searx.py+2−3
@@ -8,8 +8,7 @@ import sys
88from mock import Mock, patch
99from nose2.tools import params
1010
11−from searx.search import SearchQuery, EngineRef
12−from searx.engines import initialize_engines
11+from searx.search import SearchQuery, EngineRef, initialize
1312from searx.testing import SearxTestCase
1413
1514
@@ -30,7 +29,7 @@ class StandaloneSearx(SearxTestCase):
3029 def setUpClass(cls):
3130 engine_list = [{'engine': 'dummy', 'name': 'engine1', 'shortcut': 'e1'}]
3231
33− initialize_engines(engine_list)
32+ initialize(engine_list)
3433
3534 def test_parse_argument_no_args(self):
3635 """Test parse argument without args."""
tests/unit/test_webadapter.py+2−2
@@ -17,7 +17,7 @@ TEST_ENGINES = [
1717 'categories': 'general',
1818 'shortcut': 'do',
1919 'timeout': 3.0,
20− 'offline': True,
20+ 'engine_type': 'offline',
2121 'tokens': ['my-token'],
2222 },
2323]
@@ -28,7 +28,7 @@ class ValidateQueryCase(SearxTestCase):
2828
2929 @classmethod
3030 def setUpClass(cls):
31− searx.engines.initialize_engines(TEST_ENGINES)
31+ searx.search.initialize(TEST_ENGINES)
3232
3333 def test_query_private_engine_without_token(self):
3434 preferences = Preferences(['oscar'], ['general'], engines, [])
utils/standalone_searx.py+5−6
@@ -6,8 +6,8 @@ Getting categories without initiate the engine will only return `['general']`
66>>> import searx.engines
77... list(searx.engines.categories.keys())
88['general']
9−>>> import searx
10−... searx.engines.initialize_engines(searx.settings['engines'])
9+>>> import searx.search
10+... searx.search.initialize()
1111... list(searx.engines.categories.keys())
1212['general', 'it', 'science', 'images', 'news', 'videos', 'music', 'files', 'social media', 'map']
1313
@@ -22,11 +22,11 @@ Example to run it from python:
2222>>> import importlib
2323... import json
2424... import sys
25−... import searx
2625... import searx.engines
26+... import searx.search
2727... search_query = 'rain'
2828... # initialize engines
29−... searx.engines.initialize_engines(searx.settings['engines'])
29+... searx.search.initialize()
3030... # load engines categories once instead of each time the function called
3131... engine_cs = list(searx.engines.categories.keys())
3232... # load module
@@ -82,7 +82,6 @@ from json import dumps
8282from typing import Any, Dict, List, Optional
8383
8484import searx
85−import searx.engines
8685import searx.preferences
8786import searx.query
8887import searx.search
@@ -208,7 +207,7 @@ def parse_argument(
208207
209208
210209if __name__ == '__main__':
211− searx.engines.initialize_engines(searx.settings['engines'])
210+ searx.search.initialize()
212211 engine_cs = list(searx.engines.categories.keys())
213212 prog_args = parse_argument(category_choices=engine_cs)
214213 search_q = get_search_query(prog_args, engine_categories=engine_cs)