.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
online.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""Processors for engine-type: ``online``
3
4"""
5# pylint: disable=use-dict-literal
6
7from timeit import default_timer
8import asyncio
9import ssl
10import httpx
11
12import searx.network
13from searx.utils import gen_useragent
14from searx.exceptions import (
15 SearxEngineAccessDeniedException,
16 SearxEngineCaptchaException,
17 SearxEngineTooManyRequestsException,
18)
19from searx.metrics.error_recorder import count_error
20from .abstract import EngineProcessor
21
22
24 """Default request parameters for ``online`` engines."""
25 return {
26 # fmt: off
27 'method': 'GET',
28 'headers': {},
29 'data': {},
30 'url': '',
31 'cookies': {},
32 'auth': None
33 # fmt: on
34 }
35
36
38 """Processor class for ``online`` engines."""
39
40 engine_type = 'online'
41
42 def initialize(self):
43 # set timeout for all HTTP requests
44 searx.network.set_timeout_for_thread(self.engineengine.timeout, start_time=default_timer())
45 # reset the HTTP total time
47 # set the network
49 super().initialize()
50
51 def get_params(self, search_query, engine_category):
52 """Returns a set of :ref:`request params <engine request online>` or ``None``
53 if request is not supported.
54 """
55 params = super().get_params(search_query, engine_category)
56 if params is None:
57 return None
58
59 # add default params
60 params.update(default_request_params())
61
62 # add an user agent
63 params['headers']['User-Agent'] = gen_useragent()
64
65 # add Accept-Language header
66 if self.engineengine.send_accept_language_header and search_query.locale:
67 ac_lang = search_query.locale.language
68 if search_query.locale.territory:
69 ac_lang = "%s-%s,%s;q=0.9,*;q=0.5" % (
70 search_query.locale.language,
71 search_query.locale.territory,
72 search_query.locale.language,
73 )
74 params['headers']['Accept-Language'] = ac_lang
75
76 self.logger.debug('HTTP Accept-Language: %s', params['headers'].get('Accept-Language', ''))
77 return params
78
79 def _send_http_request(self, params):
80 # create dictionary which contain all
81 # information about the request
82 request_args = dict(headers=params['headers'], cookies=params['cookies'], auth=params['auth'])
83
84 # verify
85 # if not None, it overrides the verify value defined in the network.
86 # use False to accept any server certificate
87 # use a path to file to specify a server certificate
88 verify = params.get('verify')
89 if verify is not None:
90 request_args['verify'] = params['verify']
91
92 # max_redirects
93 max_redirects = params.get('max_redirects')
94 if max_redirects:
95 request_args['max_redirects'] = max_redirects
96
97 # allow_redirects
98 if 'allow_redirects' in params:
99 request_args['allow_redirects'] = params['allow_redirects']
100
101 # soft_max_redirects
102 soft_max_redirects = params.get('soft_max_redirects', max_redirects or 0)
103
104 # raise_for_status
105 request_args['raise_for_httperror'] = params.get('raise_for_httperror', True)
106
107 # specific type of request (GET or POST)
108 if params['method'] == 'GET':
109 req = searx.network.get
110 else:
111 req = searx.network.post
112
113 request_args['data'] = params['data']
114
115 # send the request
116 response = req(params['url'], **request_args)
117
118 # check soft limit of the redirect count
119 if len(response.history) > soft_max_redirects:
120 # unexpected redirect : record an error
121 # but the engine might still return valid results.
122 status_code = str(response.status_code or '')
123 reason = response.reason_phrase or ''
124 hostname = response.url.host
125 count_error(
127 '{} redirects, maximum: {}'.format(len(response.history), soft_max_redirects),
128 (status_code, reason, hostname),
129 secondary=True,
130 )
131
132 return response
133
134 def _search_basic(self, query, params):
135 # update request parameters dependent on
136 # search-engine (contained in engines folder)
137 self.engineengine.request(query, params)
138
139 # ignoring empty urls
140 if params['url'] is None:
141 return None
142
143 if not params['url']:
144 return None
145
146 # send request
147 response = self._send_http_request(params)
148
149 # parse the response
150 response.search_params = params
151 return self.engineengine.response(response)
152
153 def search(self, query, params, result_container, start_time, timeout_limit):
154 # set timeout for all HTTP requests
155 searx.network.set_timeout_for_thread(timeout_limit, start_time=start_time)
156 # reset the HTTP total time
158 # set the network
160
161 try:
162 # send requests and parse the results
163 search_results = self._search_basic(query, params)
164 self.extend_container(result_container, start_time, search_results)
165 except ssl.SSLError as e:
166 # requests timeout (connect or read)
167 self.handle_exception(result_container, e, suspend=True)
168 self.logger.error("SSLError {}, verify={}".format(e, searx.network.get_network(self.engine_nameengine_name).verify))
169 except (httpx.TimeoutException, asyncio.TimeoutError) as e:
170 # requests timeout (connect or read)
171 self.handle_exception(result_container, e, suspend=True)
172 self.logger.error(
173 "HTTP requests timeout (search duration : {0} s, timeout: {1} s) : {2}".format(
174 default_timer() - start_time, timeout_limit, e.__class__.__name__
175 )
176 )
177 except (httpx.HTTPError, httpx.StreamError) as e:
178 # other requests exception
179 self.handle_exception(result_container, e, suspend=True)
180 self.logger.exception(
181 "requests exception (search duration : {0} s, timeout: {1} s) : {2}".format(
182 default_timer() - start_time, timeout_limit, e
183 )
184 )
185 except SearxEngineCaptchaException as e:
186 self.handle_exception(result_container, e, suspend=True)
187 self.logger.exception('CAPTCHA')
188 except SearxEngineTooManyRequestsException as e:
189 self.handle_exception(result_container, e, suspend=True)
190 self.logger.exception('Too many requests')
191 except SearxEngineAccessDeniedException as e:
192 self.handle_exception(result_container, e, suspend=True)
193 self.logger.exception('SearXNG is blocked')
194 except Exception as e: # pylint: disable=broad-except
195 self.handle_exception(result_container, e)
196 self.logger.exception('exception : {0}'.format(e))
197
199 tests = {}
200
201 tests['simple'] = {
202 'matrix': {'query': ('life', 'computer')},
203 'result_container': ['not_empty'],
204 }
205
206 if getattr(self.engineengine, 'paging', False):
207 tests['paging'] = {
208 'matrix': {'query': 'time', 'pageno': (1, 2, 3)},
209 'result_container': ['not_empty'],
210 'test': ['unique_results'],
211 }
212 if 'general' in self.engineengine.categories:
213 # avoid documentation about HTML tags (<time> and <input type="time">)
214 tests['paging']['matrix']['query'] = 'news'
215
216 if getattr(self.engineengine, 'time_range', False):
217 tests['time_range'] = {
218 'matrix': {'query': 'news', 'time_range': (None, 'day')},
219 'result_container': ['not_empty'],
220 'test': ['unique_results'],
221 }
222
223 if getattr(self.engineengine, 'traits', False):
224 tests['lang_fr'] = {
225 'matrix': {'query': 'paris', 'lang': 'fr'},
226 'result_container': ['not_empty', ('has_language', 'fr')],
227 }
228 tests['lang_en'] = {
229 'matrix': {'query': 'paris', 'lang': 'en'},
230 'result_container': ['not_empty', ('has_language', 'en')],
231 }
232
233 if getattr(self.engineengine, 'safesearch', False):
234 tests['safesearch'] = {'matrix': {'query': 'porn', 'safesearch': (0, 2)}, 'test': ['unique_results']}
235
236 return tests
handle_exception(self, result_container, exception_or_message, suspend=False)
Definition abstract.py:85
extend_container(self, result_container, start_time, search_results)
Definition abstract.py:120
get_params(self, search_query, engine_category)
Definition online.py:51
set_context_network_name(network_name)
Definition __init__.py:39
set_timeout_for_thread(timeout, start_time=None)
Definition __init__.py:34
reset_time_for_thread()
Definition __init__.py:25