on master help sign in
[enh] replace requests by httpx
commit88a96baedc7a1e24c201cb4736fcfde50bf3cf02 authorAlexandre Flament <alex@al-f.net> dateThu 18 Mar 2021, 19:59 (6 years ago) parent4415d25
18 files changed+527−204
requirements.txt+6−1 searx/autocomplete.py+3−2 searx/engines/dictzone.py+1−1 searx/engines/elasticsearch.py+1−2 searx/engines/google.py+2−3 searx/engines/seznam.py+2−3 searx/engines/spotify.py+1−1 searx/engines/stackoverflow.py+2−3 searx/engines/yacy.py+2−2 searx/metrology/error_recorder.py+9−9 searx/poolrequests.py+414−99 searx/search/checker/impl.py+3−3 searx/search/processors/online.py+10−10 searx/settings.yml+5−3 searx/utils.py+1−1 searx/webapp.py+62−31 searx_extra/update/update_external_bangs.py+3−3 tests/unit/test_poolrequests.py−27
requirements.txt+6−1
@@ -8,5 +8,10 @@ lxml==4.6.3
88pygments==2.8.0
99python-dateutil==2.8.1
1010pyyaml==5.4.1
11−requests[socks]==2.25.1
11+httpx[http2]==0.17.1
12+Brotli==1.0.9
13+uvloop==0.15.2; python_version >= '3.7'
14+uvloop==0.14.0; python_version < '3.7'
15+httpx-socks[asyncio]==0.3.1
1216langdetect==1.0.8
17+setproctitle==1.2.2
searx/autocomplete.py+3−2
@@ -20,7 +20,8 @@ from lxml import etree
2020from json import loads
2121from urllib.parse import urlencode
2222
23−from requests import RequestException
23+from httpx import HTTPError
24+
2425
2526from searx import settings
2627from searx.poolrequests import get as http_get
@@ -136,5 +137,5 @@ def search_autocomplete(backend_name, query, lang):
136137
137138 try:
138139 return backend(query, lang)
139− except (RequestException, SearxEngineResponseException):
140+ except (HTTPError, SearxEngineResponseException):
140141 return []
searx/engines/dictzone.py+1−1
@@ -52,7 +52,7 @@ def response(resp):
5252 to_results.append(to_result.text_content())
5353
5454 results.append({
55− 'url': urljoin(resp.url, '?%d' % k),
55+ 'url': urljoin(str(resp.url), '?%d' % k),
5656 'title': from_result.text_content(),
5757 'content': '; '.join(to_results)
5858 })
searx/engines/elasticsearch.py+1−2
@@ -4,7 +4,6 @@
44"""
55
66from json import loads, dumps
7−from requests.auth import HTTPBasicAuth
87from searx.exceptions import SearxEngineAPIException
98
109
@@ -32,7 +31,7 @@ def request(query, params):
3231 return params
3332
3433 if username and password:
35− params['auth'] = HTTPBasicAuth(username, password)
34+ params['auth'] = (username, password)
3635
3736 params['url'] = search_url
3837 params['method'] = 'GET'
searx/engines/google.py+2−3
@@ -10,7 +10,7 @@ Definitions`_.
1010
1111# pylint: disable=invalid-name, missing-function-docstring
1212
13−from urllib.parse import urlencode, urlparse
13+from urllib.parse import urlencode
1414from lxml import html
1515from searx import logger
1616from searx.utils import match_language, extract_text, eval_xpath, eval_xpath_list, eval_xpath_getindex
@@ -186,8 +186,7 @@ def get_lang_info(params, lang_list, custom_aliases):
186186 return ret_val
187187
188188def detect_google_sorry(resp):
189− resp_url = urlparse(resp.url)
190− if resp_url.netloc == 'sorry.google.com' or resp_url.path.startswith('/sorry'):
189+ if resp.url.host == 'sorry.google.com' or resp.url.path.startswith('/sorry'):
191190 raise SearxEngineCaptchaException()
192191
193192
searx/engines/seznam.py+2−3
@@ -3,7 +3,7 @@
33 Seznam
44"""
55
6−from urllib.parse import urlencode, urlparse
6+from urllib.parse import urlencode
77from lxml import html
88from searx.poolrequests import get
99from searx.exceptions import SearxEngineAccessDeniedException
@@ -46,8 +46,7 @@ def request(query, params):
4646
4747
4848def response(resp):
49− resp_url = urlparse(resp.url)
50− if resp_url.path.startswith('/verify'):
49+ if resp.url.path.startswith('/verify'):
5150 raise SearxEngineAccessDeniedException()
5251
5352 results = []
searx/engines/spotify.py+1−1
@@ -5,7 +5,7 @@
55
66from json import loads
77from urllib.parse import urlencode
8−import requests
8+import searx.poolrequests as requests
99import base64
1010
1111# about
searx/engines/stackoverflow.py+2−3
@@ -3,7 +3,7 @@
33 Stackoverflow (IT)
44"""
55
6−from urllib.parse import urlencode, urljoin, urlparse
6+from urllib.parse import urlencode, urljoin
77from lxml import html
88from searx.utils import extract_text
99from searx.exceptions import SearxEngineCaptchaException
@@ -41,8 +41,7 @@ def request(query, params):
4141
4242# get response from search-request
4343def response(resp):
44− resp_url = urlparse(resp.url)
45− if resp_url.path.startswith('/nocaptcha'):
44+ if resp.url.path.startswith('/nocaptcha'):
4645 raise SearxEngineCaptchaException()
4746
4847 results = []
searx/engines/yacy.py+2−2
@@ -7,7 +7,7 @@ from json import loads
77from dateutil import parser
88from urllib.parse import urlencode
99
10−from requests.auth import HTTPDigestAuth
10+from httpx import DigestAuth
1111
1212from searx.utils import html_to_text
1313
@@ -56,7 +56,7 @@ def request(query, params):
5656 search_type=search_type)
5757
5858 if http_digest_auth_user and http_digest_auth_pass:
59− params['auth'] = HTTPDigestAuth(http_digest_auth_user, http_digest_auth_pass)
59+ params['auth'] = DigestAuth(http_digest_auth_user, http_digest_auth_pass)
6060
6161 # add language tag if specified
6262 if params['language'] != 'all':
searx/metrology/error_recorder.py+9−9
@@ -3,7 +3,7 @@ import inspect
33import logging
44from json import JSONDecodeError
55from urllib.parse import urlparse
6−from requests.exceptions import RequestException
6+from httpx import HTTPError, HTTPStatusError
77from searx.exceptions import (SearxXPathSyntaxException, SearxEngineXPathException, SearxEngineAPIException,
88 SearxEngineAccessDeniedException)
99from searx import logger
@@ -60,28 +60,28 @@ def get_trace(traces):
6060 return traces[-1]
6161
6262
63−def get_hostname(exc: RequestException) -> typing.Optional[None]:
63+def get_hostname(exc: HTTPError) -> typing.Optional[None]:
6464 url = exc.request.url
6565 if url is None and exc.response is not None:
6666 url = exc.response.url
6767 return urlparse(url).netloc
6868
6969
70−def get_request_exception_messages(exc: RequestException)\
70+def get_request_exception_messages(exc: HTTPError)\
7171 -> typing.Tuple[typing.Optional[str], typing.Optional[str], typing.Optional[str]]:
7272 url = None
7373 status_code = None
7474 reason = None
7575 hostname = None
76− if exc.request is not None:
76+ if hasattr(exc, 'request') and exc.request is not None:
7777 url = exc.request.url
78− if url is None and exc.response is not None:
78+ if url is None and hasattr(exc, 'response') and exc.respones is not None:
7979 url = exc.response.url
8080 if url is not None:
81− hostname = str(urlparse(url).netloc)
82− if exc.response is not None:
81+ hostname = url.host
82+ if isinstance(exc, HTTPStatusError):
8383 status_code = str(exc.response.status_code)
84− reason = exc.response.reason
84+ reason = exc.response.reason_phrase
8585 return (status_code, reason, hostname)
8686
8787
@@ -92,7 +92,7 @@ def get_messages(exc, filename) -> typing.Tuple:
9292 return (str(exc), )
9393 if isinstance(exc, ValueError) and 'lxml' in filename:
9494 return (str(exc), )
95− if isinstance(exc, RequestException):
95+ if isinstance(exc, HTTPError):
9696 return get_request_exception_messages(exc)
9797 if isinstance(exc, SearxXPathSyntaxException):
9898 return (exc.xpath_str, exc.message)
searx/poolrequests.py+414−99
@@ -1,14 +1,54 @@
1+import atexit
12import sys
3+import threading
4+import asyncio
5+import logging
6+import concurrent.futures
27from time import time
38from itertools import cycle
4−from threading import local
59
6−import requests
10+import httpcore
11+import httpx
12+import h2.exceptions
13+from httpx_socks import AsyncProxyTransport
14+from python_socks import parse_proxy_url
15+import python_socks._errors
716
817from searx import settings
918from searx import logger
1019from searx.raise_for_httperror import raise_for_httperror
1120
21+# Optional uvloop (support Python 3.6)
22+try:
23+ import uvloop
24+except ImportError:
25+ pass
26+else:
27+ uvloop.install()
28+
29+# queue.SimpleQueue: Support Python 3.6
30+try:
31+ from queue import SimpleQueue
32+except ImportError:
33+ from queue import Empty
34+ from collections import deque
35+
36+ class SimpleQueue:
37+ """Minimal backport of queue.SimpleQueue"""
38+
39+ def __init__(self):
40+ self._queue = deque()
41+ self._count = threading.Semaphore(0)
42+
43+ def put(self, item):
44+ self._queue.append(item)
45+ self._count.release()
46+
47+ def get(self, timeout=None):
48+ if not self._count.acquire(True, timeout):
49+ raise Empty
50+ return self._queue.popleft()
51+
1252
1353logger = logger.getChild('poolrequests')
1454
@@ -31,99 +71,63 @@ if not getattr(ssl, "HAS_SNI", False):
3171 sys.exit(1)
3272
3373
34−class HTTPAdapterWithConnParams(requests.adapters.HTTPAdapter):
35−
36− def __init__(self, pool_connections=requests.adapters.DEFAULT_POOLSIZE,
37− pool_maxsize=requests.adapters.DEFAULT_POOLSIZE,
38− max_retries=requests.adapters.DEFAULT_RETRIES,
39− pool_block=requests.adapters.DEFAULT_POOLBLOCK,
40− **conn_params):
41− if max_retries == requests.adapters.DEFAULT_RETRIES:
42− self.max_retries = requests.adapters.Retry(0, read=False)
43− else:
44− self.max_retries = requests.adapters.Retry.from_int(max_retries)
45− self.config = {}
46− self.proxy_manager = {}
47−
48− super().__init__()
49−
50− self._pool_connections = pool_connections
51− self._pool_maxsize = pool_maxsize
52− self._pool_block = pool_block
53− self._conn_params = conn_params
54−
55− self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block, **conn_params)
56−
57− def __setstate__(self, state):
58− # Can't handle by adding 'proxy_manager' to self.__attrs__ because
59− # because self.poolmanager uses a lambda function, which isn't pickleable.
60− self.proxy_manager = {}
61− self.config = {}
62−
63− for attr, value in state.items():
64− setattr(self, attr, value)
74+LOOP = None
75+CLIENTS = dict()
76+THREADLOCAL = threading.local()
77+LIMITS = httpx.Limits(
78+ # Magic number kept from previous code
79+ max_connections=settings['outgoing'].get('pool_connections', 100),
80+ # Picked from constructor
81+ max_keepalive_connections=settings['outgoing'].get('pool_maxsize', 10),
82+ #
83+ keepalive_expiry=settings['outgoing'].get('keepalive_expiry', 5.0)
84+)
85+# default parameters for AsyncHTTPTransport
86+# see https://github.com/encode/httpx/blob/e05a5372eb6172287458b37447c30f650047e1b8/httpx/_transports/default.py#L108-L121 # noqa
87+TRANSPORT_KWARGS = {
88+ 'http2': settings['outgoing'].get('http2', False),
89+ 'retries': 0,
90+ 'trust_env': False,
91+ 'backend': 'asyncio'
92+}
93+# requests compatibility when reading proxy settings from settings.yml
94+PROXY_PATTERN_MAPPING = {
95+ 'http': 'https://',
96+ 'https:': 'https://'
97+}
98+# default maximum redirect
99+# from https://github.com/psf/requests/blob/8c211a96cdbe9fe320d63d9e1ae15c5c07e179f8/requests/models.py#L55
100+DEFAULT_REDIRECT_LIMIT = 30
65101
66− self.init_poolmanager(self._pool_connections, self._pool_maxsize,
67− block=self._pool_block, **self._conn_params)
68102
69−
70−threadLocal = local()
71−connect = settings['outgoing'].get('pool_connections', 100) # Magic number kept from previous code
72−maxsize = settings['outgoing'].get('pool_maxsize', requests.adapters.DEFAULT_POOLSIZE) # Picked from constructor
73103if settings['outgoing'].get('source_ips'):
74− http_adapters = cycle(HTTPAdapterWithConnParams(pool_connections=connect, pool_maxsize=maxsize,
75− source_address=(source_ip, 0))
76− for source_ip in settings['outgoing']['source_ips'])
77− https_adapters = cycle(HTTPAdapterWithConnParams(pool_connections=connect, pool_maxsize=maxsize,
78− source_address=(source_ip, 0))
79− for source_ip in settings['outgoing']['source_ips'])
104+ LOCAL_ADDRESS_CYCLE = cycle(settings['outgoing'].get('source_ips'))
80105else:
81− http_adapters = cycle((HTTPAdapterWithConnParams(pool_connections=connect, pool_maxsize=maxsize), ))
82− https_adapters = cycle((HTTPAdapterWithConnParams(pool_connections=connect, pool_maxsize=maxsize), ))
83−
84−
85−class SessionSinglePool(requests.Session):
86−
87− def __init__(self):
88− super().__init__()
89−
90− # reuse the same adapters
91− self.adapters.clear()
92−
93− https_adapter = threadLocal.__dict__.setdefault('https_adapter', next(https_adapters))
94− self.mount('https://', https_adapter)
95− if get_enable_http_protocol():
96− http_adapter = threadLocal.__dict__.setdefault('http_adapter', next(http_adapters))
97− self.mount('http://', http_adapter)
98−
99− def close(self):
100− """Call super, but clear adapters since there are managed globaly"""
101− self.adapters.clear()
102− super().close()
106+ LOCAL_ADDRESS_CYCLE = cycle((None, ))
103107
104108
105109def set_timeout_for_thread(timeout, start_time=None):
106− threadLocal.timeout = timeout
107− threadLocal.start_time = start_time
110+ THREADLOCAL.timeout = timeout
111+ THREADLOCAL.start_time = start_time
108112
109113
110114def set_enable_http_protocol(enable_http):
111− threadLocal.enable_http = enable_http
115+ THREADLOCAL.enable_http = enable_http
112116
113117
114118def get_enable_http_protocol():
115119 try:
116− return threadLocal.enable_http
120+ return THREADLOCAL.enable_http
117121 except AttributeError:
118122 return False
119123
120124
121125def reset_time_for_thread():
122− threadLocal.total_time = 0
126+ THREADLOCAL.total_time = 0
123127
124128
125129def get_time_for_thread():
126− return threadLocal.total_time
130+ return THREADLOCAL.total_time
127131
128132
129133def get_proxy_cycles(proxy_settings):
@@ -152,22 +156,197 @@ def get_global_proxies():
152156 return get_proxies(GLOBAL_PROXY_CYCLES)
153157
154158
159+async def close_connections_for_url(connection_pool: httpcore.AsyncConnectionPool, url: httpcore._utils.URL):
160+ origin = httpcore._utils.url_to_origin(url)
161+ logger.debug('Drop connections for %r', origin)
162+ connections_to_close = connection_pool._connections_for_origin(origin)
163+ for connection in connections_to_close:
164+ await connection_pool._remove_from_pool(connection)
165+ try:
166+ await connection.aclose()
167+ except httpcore.NetworkError as e:
168+ logger.warning('Error closing an existing connection', exc_info=e)
169+
170+
171+class AsyncHTTPTransportNoHttp(httpcore.AsyncHTTPTransport):
172+ """Block HTTP request"""
173+
174+ async def arequest(self, method, url, headers=None, stream=None, ext=None):
175+ raise httpcore.UnsupportedProtocol("HTTP protocol is disabled")
176+
177+
178+class AsyncProxyTransportFixed(AsyncProxyTransport):
179+ """Fix httpx_socks.AsyncProxyTransport
180+
181+ Map python_socks exceptions to httpcore.ProxyError
182+
183+ Map socket.gaierror to httpcore.ConnectError
184+
185+ Note: keepalive_expiry is ignored, AsyncProxyTransport should call:
186+ * self._keepalive_sweep()
187+ * self._response_closed(self, connection)
188+
189+ Note: AsyncProxyTransport inherit from AsyncConnectionPool
190+
191+ Note: the API is going to change on httpx 0.18.0
192+ see https://github.com/encode/httpx/pull/1522
193+ """
194+
195+ async def arequest(self, method, url, headers=None, stream=None, ext=None):
196+ retry = 2
197+ while retry > 0:
198+ retry -= 1
199+ try:
200+ return await super().arequest(method, url, headers, stream, ext)
201+ except (python_socks._errors.ProxyConnectionError,
202+ python_socks._errors.ProxyTimeoutError,
203+ python_socks._errors.ProxyError) as e:
204+ raise httpcore.ProxyError(e)
205+ except OSError as e:
206+ # socket.gaierror when DNS resolution fails
207+ raise httpcore.NetworkError(e)
208+ except httpcore.RemoteProtocolError as e:
209+ # in case of httpcore.RemoteProtocolError: Server disconnected
210+ await close_connections_for_url(self, url)
211+ logger.warning('httpcore.RemoteProtocolError: retry', exc_info=e)
212+ # retry
213+ except (httpcore.NetworkError, httpcore.ProtocolError) as e:
214+ # httpcore.WriteError on HTTP/2 connection leaves a new opened stream
215+ # then each new request creates a new stream and raise the same WriteError
216+ await close_connections_for_url(self, url)
217+ raise e
218+
219+
220+class AsyncHTTPTransportFixed(httpx.AsyncHTTPTransport):
221+ """Fix httpx.AsyncHTTPTransport"""
222+
223+ async def arequest(self, method, url, headers=None, stream=None, ext=None):
224+ retry = 2
225+ while retry > 0:
226+ retry -= 1
227+ try:
228+ return await super().arequest(method, url, headers, stream, ext)
229+ except OSError as e:
230+ # socket.gaierror when DNS resolution fails
231+ raise httpcore.ConnectError(e)
232+ except httpcore.CloseError as e:
233+ # httpcore.CloseError: [Errno 104] Connection reset by peer
234+ # raised by _keepalive_sweep()
235+ # from https://github.com/encode/httpcore/blob/4b662b5c42378a61e54d673b4c949420102379f5/httpcore/_backends/asyncio.py#L198 # noqa
236+ await close_connections_for_url(self._pool, url)
237+ logger.warning('httpcore.CloseError: retry', exc_info=e)
238+ # retry
239+ except httpcore.RemoteProtocolError as e:
240+ # in case of httpcore.RemoteProtocolError: Server disconnected
241+ await close_connections_for_url(self._pool, url)
242+ logger.warning('httpcore.RemoteProtocolError: retry', exc_info=e)
243+ # retry
244+ except (httpcore.ProtocolError, httpcore.NetworkError) as e:
245+ await close_connections_for_url(self._pool, url)
246+ raise e
247+
248+
249+def get_transport_for_socks_proxy(verify, local_address, proxy_url):
250+ global LOOP, LIMITS, TRANSPORT_KWARGS
251+ # support socks5h (requests compatibility):
252+ # https://requests.readthedocs.io/en/master/user/advanced/#socks
253+ # socks5:// hostname is resolved on client side
254+ # socks5h:// hostname is resolved on proxy side
255+ rdns = False
256+ socks5h = 'socks5h://'
257+ if proxy_url.startswith(socks5h):
258+ proxy_url = 'socks5://' + proxy_url[len(socks5h):]
259+ rdns = True
260+
261+ proxy_type, proxy_host, proxy_port, proxy_username, proxy_password = parse_proxy_url(proxy_url)
262+
263+ return AsyncProxyTransportFixed(proxy_type=proxy_type, proxy_host=proxy_host, proxy_port=proxy_port,
264+ username=proxy_username, password=proxy_password,
265+ rdns=rdns,
266+ loop=LOOP,
267+ verify=verify,
268+ local_address=local_address,
269+ max_connections=LIMITS.max_connections,
270+ max_keepalive_connections=LIMITS.max_keepalive_connections,
271+ keepalive_expiry=LIMITS.keepalive_expiry,
272+ **TRANSPORT_KWARGS)
273+
274+
275+def get_transport(verify, local_address, proxy_url):
276+ global LIMITS
277+ return AsyncHTTPTransportFixed(verify=verify,
278+ local_address=local_address,
279+ limits=LIMITS,
280+ proxy=httpx._config.Proxy(proxy_url) if proxy_url else None,
281+ **TRANSPORT_KWARGS)
282+
283+
284+def iter_proxies(proxies):
285+ # https://www.python-httpx.org/compatibility/#proxy-keys
286+ if isinstance(proxies, str):
287+ yield 'all://', proxies
288+ elif isinstance(proxies, dict):
289+ for pattern, proxy_url in proxies.items():
290+ pattern = PROXY_PATTERN_MAPPING.get(pattern, pattern)
291+ yield pattern, proxy_url
292+
293+
294+def new_client(verify, local_address, proxies, max_redirects, enable_http):
295+ # See https://www.python-httpx.org/advanced/#routing
296+ mounts = {}
297+ for pattern, proxy_url in iter_proxies(proxies):
298+ if not enable_http and (pattern == 'http' or pattern.startswith('http://')):
299+ continue
300+ if proxy_url.startswith('socks4://') \
301+ or proxy_url.startswith('socks5://') \
302+ or proxy_url.startswith('socks5h://'):
303+ mounts[pattern] = get_transport_for_socks_proxy(verify, local_address, proxy_url)
304+ else:
305+ mounts[pattern] = get_transport(verify, local_address, proxy_url)
306+
307+ if not enable_http:
308+ mounts['http://'] = AsyncHTTPTransportNoHttp()
309+
310+ transport = get_transport(verify, local_address, None)
311+ return httpx.AsyncClient(transport=transport, mounts=mounts, max_redirects=max_redirects)
312+
313+
314+def get_client(verify, local_address, proxies, max_redirects, allow_http):
315+ global CLIENTS
316+ key = (verify, local_address, repr(proxies), max_redirects, allow_http)
317+ if key not in CLIENTS:
318+ CLIENTS[key] = new_client(verify, local_address, proxies, max_redirects, allow_http)
319+ return CLIENTS[key]
320+
321+
322+async def send_request(method, url, enable_http, kwargs):
323+ if isinstance(url, bytes):
324+ url = url.decode()
325+
326+ verify = kwargs.pop('verify', True)
327+ local_address = next(LOCAL_ADDRESS_CYCLE)
328+ proxies = kwargs.pop('proxies', None) or get_global_proxies()
329+ max_redirects = kwargs.pop('max_redirects', DEFAULT_REDIRECT_LIMIT)
330+
331+ client = get_client(verify, local_address, proxies, max_redirects, enable_http)
332+ response = await client.request(method.upper(), url, **kwargs)
333+
334+ # requests compatibility
335+ # see also https://www.python-httpx.org/compatibility/#checking-for-4xx5xx-responses
336+ response.ok = not response.is_error
337+
338+ return response
339+
340+
155341def request(method, url, **kwargs):
156342 """same as requests/requests/api.py request(...)"""
157343 time_before_request = time()
158344
159− # session start
160− session = SessionSinglePool()
161−
162− # proxies
163− if not kwargs.get('proxies'):
164− kwargs['proxies'] = get_global_proxies()
165−
166345 # timeout
167346 if 'timeout' in kwargs:
168347 timeout = kwargs['timeout']
169348 else:
170− timeout = getattr(threadLocal, 'timeout', None)
349+ timeout = getattr(THREADLOCAL, 'timeout', None)
171350 if timeout is not None:
172351 kwargs['timeout'] = timeout
173352
@@ -178,24 +357,23 @@ def request(method, url, **kwargs):
178357 del kwargs['raise_for_httperror']
179358
180359 # do request
181− response = session.request(method=method, url=url, **kwargs)
182−
183− time_after_request = time()
184−
185− # is there a timeout for this engine ?
186− if timeout is not None:
187− timeout_overhead = 0.2 # seconds
188− # start_time = when the user request started
189− start_time = getattr(threadLocal, 'start_time', time_before_request)
190− search_duration = time_after_request - start_time
191− if search_duration > timeout + timeout_overhead:
192− raise requests.exceptions.Timeout(response=response)
193−
194− # session end
195− session.close()
196−
197− if hasattr(threadLocal, 'total_time'):
198− threadLocal.total_time += time_after_request - time_before_request
360+ future = asyncio.run_coroutine_threadsafe(send_request(method, url, get_enable_http_protocol(), kwargs), LOOP)
361+ try:
362+ if timeout:
363+ timeout += 0.2 # overhead
364+ start_time = getattr(THREADLOCAL, 'start_time', time_before_request)
365+ if start_time:
366+ timeout -= time() - start_time
367+
368+ response = future.result(timeout or 120)
369+ except concurrent.futures.TimeoutError as e:
370+ raise httpx.TimeoutException('Timeout', request=None) from e
371+
372+ # update total_time.
373+ # See get_time_for_thread() and reset_time_for_thread()
374+ if hasattr(THREADLOCAL, 'total_time'):
375+ time_after_request = time()
376+ THREADLOCAL.total_time += time_after_request - time_before_request
199377
200378 # raise an exception
201379 if check_for_httperror:
@@ -204,6 +382,49 @@ def request(method, url, **kwargs):
204382 return response
205383
206384
385+async def stream_chunk_to_queue(method, url, q, **kwargs):
386+ verify = kwargs.pop('verify', True)
387+ local_address = next(LOCAL_ADDRESS_CYCLE)
388+ proxies = kwargs.pop('proxies', None) or get_global_proxies()
389+ # "30" from requests:
390+ # https://github.com/psf/requests/blob/8c211a96cdbe9fe320d63d9e1ae15c5c07e179f8/requests/models.py#L55
391+ max_redirects = kwargs.pop('max_redirects', 30)
392+ client = get_client(verify, local_address, proxies, max_redirects, True)
393+ try:
394+ async with client.stream(method, url, **kwargs) as response:
395+ q.put(response)
396+ async for chunk in response.aiter_bytes(65536):
397+ if len(chunk) > 0:
398+ q.put(chunk)
399+ except (httpx.HTTPError, OSError, h2.exceptions.ProtocolError) as e:
400+ q.put(e)
401+ finally:
402+ q.put(None)
403+
404+
405+def stream(method, url, **kwargs):
406+ """Replace httpx.stream.
407+
408+ Usage:
409+ stream = poolrequests.stream(...)
410+ response = next(stream)
411+ for chunk in stream:
412+ ...
413+
414+ httpx.Client.stream requires to write the httpx.HTTPTransport version of the
415+ the httpx.AsyncHTTPTransport declared above.
416+ """
417+ q = SimpleQueue()
418+ future = asyncio.run_coroutine_threadsafe(stream_chunk_to_queue(method, url, q, **kwargs), LOOP)
419+ chunk_or_exception = q.get(timeout=60)
420+ while chunk_or_exception is not None:
421+ if isinstance(chunk_or_exception, Exception):
422+ raise chunk_or_exception
423+ yield chunk_or_exception
424+ chunk_or_exception = q.get(timeout=60)
425+ return future.result()
426+
427+
207428def get(url, **kwargs):
208429 kwargs.setdefault('allow_redirects', True)
209430 return request('get', url, **kwargs)
@@ -233,3 +454,97 @@ def patch(url, data=None, **kwargs):
233454
234455def delete(url, **kwargs):
235456 return request('delete', url, **kwargs)
457+
458+
459+def init():
460+ # log
461+ for logger_name in ('hpack.hpack', 'hpack.table'):
462+ logging.getLogger(logger_name).setLevel(logging.WARNING)
463+
464+ # loop
465+ def loop_thread():
466+ global LOOP
467+ LOOP = asyncio.new_event_loop()
468+ LOOP.run_forever()
469+
470+ th = threading.Thread(
471+ target=loop_thread,
472+ name='asyncio_loop',
473+ daemon=True,
474+ )
475+ th.start()
476+
477+
478+@atexit.register
479+def done():
480+ """Close all HTTP client
481+
482+ Avoid a warning at exit
483+ see https://github.com/encode/httpx/blob/1a6e254f72d9fd5694a1c10a28927e193ab4f76b/httpx/_client.py#L1785
484+ """
485+ global LOOP
486+
487+ async def close_client(client):
488+ try:
489+ await client.aclose()
490+ except httpx.HTTPError:
491+ pass
492+
493+ async def close_clients():
494+ await asyncio.gather(*[close_client(client) for client in CLIENTS.values()], return_exceptions=False)
495+ future = asyncio.run_coroutine_threadsafe(close_clients(), LOOP)
496+ # wait 3 seconds to close the HTTP clients
497+ future.result(3)
498+
499+
500+init()
501+
502+
503+# ## TEMPORARY DEBUG ##
504+
505+
506+def debug_connection(connection):
507+ now = LOOP.time()
508+ expired = (connection.state == httpcore._async.base.ConnectionState.IDLE
509+ and connection.expires_at is not None
510+ and now >= connection.expires_at)
511+ return connection.info()\
512+ + (', connect_failed' if connection.connect_failed else '')\
513+ + (', expired' if expired else '')
514+
515+
516+def debug_origin(origin):
517+ return origin[0].decode() + '://' + origin[1].decode() + ':' + str(origin[2])
518+
519+
520+def debug_transport(transport):
521+ result = {
522+ '__class__': str(transport.__class__.__name__)
523+ }
524+ if isinstance(transport, (httpx.AsyncHTTPTransport, AsyncHTTPTransportFixed)):
525+ pool = transport._pool
526+ result['__pool_class__'] = str(pool.__class__.__name__)
527+ if isinstance(pool, httpcore.AsyncConnectionPool):
528+ for origin, connections in pool._connections.items():
529+ result[debug_origin(origin)] = [debug_connection(connection) for connection in connections]
530+ return result
531+ elif isinstance(transport, AsyncProxyTransportFixed):
532+ for origin, connections in transport._connections.items():
533+ result[debug_origin(origin)] = [debug_connection(connection) for connection in connections]
534+ return result
535+ return result
536+
537+
538+def debug_asyncclient(client, key=None):
539+ result = {}
540+ if key:
541+ result['__key__'] = [k if isinstance(k, (str, int, float, bool, type(None))) else repr(k) for k in key]
542+ result['__default__'] = debug_transport(client._transport)
543+ for urlpattern, transport in client._mounts.items():
544+ result[urlpattern.pattern] = debug_transport(transport)
545+ return result
546+
547+
548+def debug_asyncclients():
549+ global CLIENTS
550+ return [debug_asyncclient(client, key) for key, client in CLIENTS.items()]
searx/search/checker/impl.py+3−3
@@ -11,7 +11,7 @@ from urllib.parse import urlparse
1111import re
1212from langdetect import detect_langs
1313from langdetect.lang_detect_exception import LangDetectException
14−import requests.exceptions
14+import httpx
1515
1616from searx import poolrequests, logger
1717from searx.results import ResultContainer
@@ -90,10 +90,10 @@ def _is_url_image(image_url):
9090 if r.headers["content-type"].startswith('image/'):
9191 return True
9292 return False
93− except requests.exceptions.Timeout:
93+ except httpx.TimeoutException:
9494 logger.error('Timeout for %s: %i', image_url, int(time() - a))
9595 retry -= 1
96− except requests.exceptions.RequestException:
96+ except httpx.HTTPError:
9797 logger.exception('Exception for %s', image_url)
9898 return False
9999
searx/search/processors/online.py+10−10
@@ -1,10 +1,10 @@
11# SPDX-License-Identifier: AGPL-3.0-or-later
22
3−from urllib.parse import urlparse
43from time import time
54import threading
5+import asyncio
66
7−import requests.exceptions
7+import httpx
88
99import searx.poolrequests as poolrequests
1010from searx.engines import settings
@@ -99,8 +99,8 @@ class OnlineProcessor(EngineProcessor):
9999 # unexpected redirect : record an error
100100 # but the engine might still return valid results.
101101 status_code = str(response.status_code or '')
102− reason = response.reason or ''
103− hostname = str(urlparse(response.url or '').netloc)
102+ reason = response.reason_phrase or ''
103+ hostname = response.url.host
104104 record_error(self.engine_name,
105105 '{} redirects, maximum: {}'.format(len(response.history), soft_max_redirects),
106106 (status_code, reason, hostname))
@@ -135,7 +135,7 @@ class OnlineProcessor(EngineProcessor):
135135 poolrequests.set_enable_http_protocol(self.engine.enable_http)
136136
137137 # suppose everything will be alright
138− requests_exception = False
138+ http_exception = False
139139 suspended_time = None
140140
141141 try:
@@ -169,20 +169,20 @@ class OnlineProcessor(EngineProcessor):
169169 with threading.RLock():
170170 self.engine.stats['errors'] += 1
171171
172− if (issubclass(e.__class__, requests.exceptions.Timeout)):
172+ if (issubclass(e.__class__, (httpx.TimeoutException, asyncio.TimeoutError))):
173173 result_container.add_unresponsive_engine(self.engine_name, 'HTTP timeout')
174174 # requests timeout (connect or read)
175175 logger.error("engine {0} : HTTP requests timeout"
176176 "(search duration : {1} s, timeout: {2} s) : {3}"
177177 .format(self.engine_name, engine_time, timeout_limit, e.__class__.__name__))
178− requests_exception = True
179− elif (issubclass(e.__class__, requests.exceptions.RequestException)):
178+ http_exception = True
179+ elif (issubclass(e.__class__, (httpx.HTTPError, httpx.StreamError))):
180180 result_container.add_unresponsive_engine(self.engine_name, 'HTTP error')
181181 # other requests exception
182182 logger.exception("engine {0} : requests exception"
183183 "(search duration : {1} s, timeout: {2} s) : {3}"
184184 .format(self.engine_name, engine_time, timeout_limit, e))
185− requests_exception = True
185+ http_exception = True
186186 elif (issubclass(e.__class__, SearxEngineCaptchaException)):
187187 result_container.add_unresponsive_engine(self.engine_name, 'CAPTCHA required')
188188 logger.exception('engine {0} : CAPTCHA'.format(self.engine_name))
@@ -206,7 +206,7 @@ class OnlineProcessor(EngineProcessor):
206206 # suspend the engine if there is an HTTP error
207207 # or suspended_time is defined
208208 with threading.RLock():
209− if requests_exception or suspended_time:
209+ if http_exception or suspended_time:
210210 # update continuous_errors / suspend_end_time
211211 self.engine.continuous_errors += 1
212212 if suspended_time is None:
searx/settings.yml+5−3
@@ -67,11 +67,13 @@ ui:
6767# key : !!binary "your_morty_proxy_key"
6868
6969outgoing: # communication with search engines
70− request_timeout : 2.0 # default timeout in seconds, can be override by engine
70+ request_timeout : 3.0 # default timeout in seconds, can be override by engine
7171 # max_request_timeout: 10.0 # the maximum timeout in seconds
7272 useragent_suffix : "" # suffix of searx_useragent, could contain informations like an email address to the administrator
73− pool_connections : 100 # Number of different hosts
74− pool_maxsize : 10 # Number of simultaneous requests by host
73+ pool_connections : 100 # The maximum number of concurrent connections that may be established.
74+ pool_maxsize : 20 # Allow the connection pool to maintain keep-alive connections below this point.
75+ keepalive_expiry: 30.0 # Number of seconds to keep a connection in the pool
76+ http2: True # Enable HTTP/2 (experimental)
7577# uncomment below section if you want to use a proxy
7678# see https://2.python-requests.org/en/latest/user/advanced/#proxies
7779# SOCKS proxies are also supported: see https://2.python-requests.org/en/latest/user/advanced/#socks
searx/utils.py+1−1
@@ -45,7 +45,7 @@ def searx_useragent():
4545 """Return the searx User Agent"""
4646 return 'searx/{searx_version} {suffix}'.format(
4747 searx_version=VERSION_STRING,
48− suffix=settings['outgoing'].get('useragent_suffix', ''))
48+ suffix=settings['outgoing'].get('useragent_suffix', '')).strip()
4949
5050
5151def gen_useragent(os=None):
searx/webapp.py+62−31
@@ -26,12 +26,26 @@ if __name__ == '__main__':
2626 from os.path import realpath, dirname
2727 sys.path.append(realpath(dirname(realpath(__file__)) + '/../'))
2828
29+# set Unix thread name
30+try:
31+ import setproctitle
32+except ImportError:
33+ pass
34+else:
35+ import threading
36+ old_thread_init = threading.Thread.__init__
37+
38+ def new_thread_init(self, *args, **kwargs):
39+ old_thread_init(self, *args, **kwargs)
40+ setproctitle.setthreadtitle(self._name)
41+ threading.Thread.__init__ = new_thread_init
42+
2943import hashlib
3044import hmac
3145import json
3246import os
3347
34−import requests
48+import httpx
3549
3650from searx import logger
3751logger = logger.getChild('webapp')
@@ -79,7 +93,7 @@ from searx.plugins import plugins
7993from searx.plugins.oa_doi_rewrite import get_doi_resolver
8094from searx.preferences import Preferences, ValidationException, LANGUAGE_CODES
8195from searx.answerers import answerers
82−from searx.poolrequests import get_global_proxies
96+from searx import poolrequests
8397from searx.answerers import ask
8498from searx.metrology.error_recorder import errors_per_engines
8599
@@ -899,50 +913,62 @@ def _is_selected_language_supported(engine, preferences):
899913
900914@app.route('/image_proxy', methods=['GET'])
901915def image_proxy():
902− url = request.args.get('url').encode()
916+ url = request.args.get('url')
903917
904918 if not url:
905919 return '', 400
906920
907− h = new_hmac(settings['server']['secret_key'], url)
921+ h = new_hmac(settings['server']['secret_key'], url.encode())
908922
909923 if h != request.args.get('h'):
910924 return '', 400
911925
912− headers = dict_subset(request.headers, {'If-Modified-Since', 'If-None-Match'})
913− headers['User-Agent'] = gen_useragent()
914−
915− resp = requests.get(url,
916− stream=True,
917− timeout=settings['outgoing']['request_timeout'],
918− headers=headers,
919− proxies=get_global_proxies())
926+ maximum_size = 5 * 1024 * 1024
920927
921− if resp.status_code == 304:
922− return '', resp.status_code
923−
924− if resp.status_code != 200:
925− logger.debug('image-proxy: wrong response code: {0}'.format(resp.status_code))
926− if resp.status_code >= 400:
928+ try:
929+ headers = dict_subset(request.headers, {'If-Modified-Since', 'If-None-Match'})
930+ headers['User-Agent'] = gen_useragent()
931+ stream = poolrequests.stream(
932+ method='GET',
933+ url=url,
934+ headers=headers,
935+ timeout=settings['outgoing']['request_timeout'],
936+ allow_redirects=True,
937+ max_redirects=20)
938+
939+ resp = next(stream)
940+ content_length = resp.headers.get('Content-Length')
941+ if content_length and content_length.isdigit() and int(content_length) > maximum_size:
942+ return 'Max size', 400
943+
944+ if resp.status_code == 304:
927945 return '', resp.status_code
928− return '', 400
929946
930− if not resp.headers.get('content-type', '').startswith('image/'):
931− logger.debug('image-proxy: wrong content-type: {0}'.format(resp.headers.get('content-type')))
932− return '', 400
947+ if resp.status_code != 200:
948+ logger.debug('image-proxy: wrong response code: {0}'.format(resp.status_code))
949+ if resp.status_code >= 400:
950+ return '', resp.status_code
951+ return '', 400
952+
953+ if not resp.headers.get('content-type', '').startswith('image/'):
954+ logger.debug('image-proxy: wrong content-type: {0}'.format(resp.headers.get('content-type')))
955+ return '', 400
933956
934− img = b''
935− chunk_counter = 0
957+ headers = dict_subset(resp.headers, {'Content-Length', 'Length', 'Date', 'Last-Modified', 'Expires', 'Etag'})
936958
937− for chunk in resp.iter_content(1024 * 1024):
938− chunk_counter += 1
939− if chunk_counter > 5:
940− return '', 502 # Bad gateway - file is too big (>5M)
941− img += chunk
959+ total_length = 0
942960
943− headers = dict_subset(resp.headers, {'Content-Length', 'Length', 'Date', 'Last-Modified', 'Expires', 'Etag'})
961+ def forward_chunk():
962+ nonlocal total_length
963+ for chunk in stream:
964+ total_length += len(chunk)
965+ if total_length > maximum_size:
966+ break
967+ yield chunk
944968
945− return Response(img, mimetype=resp.headers['content-type'], headers=headers)
969+ return Response(forward_chunk(), mimetype=resp.headers['Content-Type'], headers=headers)
970+ except httpx.HTTPError:
971+ return '', 400
946972
947973
948974@app.route('/stats', methods=['GET'])
@@ -1092,6 +1118,11 @@ def config():
10921118 })
10931119
10941120
1121+@app.route('/config/http')
1122+def config_http():
1123+ return jsonify(poolrequests.debug_asyncclients())
1124+
1125+
10951126@app.errorhandler(404)
10961127def page_not_found(e):
10971128 return render('404.html'), 404
searx_extra/update/update_external_bangs.py+3−3
@@ -17,7 +17,7 @@ import json
1717import re
1818from os.path import join
1919
20−import requests
20+import httpx
2121
2222from searx import searx_dir # pylint: disable=E0401 C0413
2323
@@ -30,7 +30,7 @@ HTTP_COLON = 'http:'
3030
3131
3232def get_bang_url():
33− response = requests.get(URL_BV1)
33+ response = httpx.get(URL_BV1)
3434 response.raise_for_status()
3535
3636 r = RE_BANG_VERSION.findall(response.text)
@@ -38,7 +38,7 @@ def get_bang_url():
3838
3939
4040def fetch_ddg_bangs(url):
41− response = requests.get(url)
41+ response = httpx.get(url)
4242 response.raise_for_status()
4343 return json.loads(response.content.decode())
4444
tests/unit/test_poolrequests.py−27
@@ -1,9 +1,5 @@
1−from unittest.mock import patch
2−from requests.models import Response
3−
41from searx.testing import SearxTestCase
52
6−import searx.poolrequests
73from searx.poolrequests import get_proxy_cycles, get_proxies
84
95
@@ -64,26 +60,3 @@ class TestProxy(SearxTestCase):
6460 'http': 'http://localhost:9092',
6561 'https': 'http://localhost:9093'
6662 })
67−
68− @patch('searx.poolrequests.get_global_proxies')
69− def test_request(self, mock_get_global_proxies):
70− method = 'GET'
71− url = 'http://localhost'
72− custom_proxies = {
73− 'https': 'http://localhost:1080'
74− }
75− global_proxies = {
76− 'http': 'http://localhost:9092',
77− 'https': 'http://localhost:9093'
78− }
79− mock_get_global_proxies.return_value = global_proxies
80−
81− # check the global proxies usage
82− with patch.object(searx.poolrequests.SessionSinglePool, 'request', return_value=Response()) as mock_method:
83− searx.poolrequests.request(method, url)
84− mock_method.assert_called_once_with(method=method, url=url, proxies=global_proxies)
85−
86− # check if the proxies parameter overrides the global proxies
87− with patch.object(searx.poolrequests.SessionSinglePool, 'request', return_value=Response()) as mock_method:
88− searx.poolrequests.request(method, url, proxies=custom_proxies)
89− mock_method.assert_called_once_with(method=method, url=url, proxies=custom_proxies)