# Buggy code
def search_one_offline_request_safe(
    engine_name, query, request_params, result_container, start_time, timeout_limit
):
    engine = engines[engine_name]

    try:
        search_results = search_one_offline_request(engine, query, request_params)

        if search_results:
            result_container.extend(engine_name, search_results)

            engine_time = time() - start_time
            result_container.add_timing(engine_name, engine_time, engine_time)
            with threading.RLock():
                engine.stats["engine_time"] += engine_time
                engine.stats["engine_time_count"] += 1

    except ValueError as e:
        record_offline_engine_stats_on_error(engine, result_container, start_time)
        logger.exception("engine {0} : invalid input : {1}".format(engine_name, e))
    except Exception as e:
        record_offline_engine_stats_on_error(engine, result_container, start_time)

        result_container.add_unresponsive_engine(
            (
                engine_name,
                "{0}: {1}".format(gettext("unexpected crash"), e),
            )
        )
        logger.exception("engine {0} : exception : {1}".format(engine_name, e))


# Traceback (urllib3.exceptions.ReadTimeoutError)
Exception in thread aeb1ee8b-0fe7-4e90-8f29-0c487673c1eb:
Traceback (most recent call last):
File "/home/n/p/searx/venv3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 421, in _make_request
six.raise_from(e, None)
File "<string>", line 3, in raise_from
File "/home/n/p/searx/venv3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 416, in _make_request
httplib_response = conn.getresponse()
File "/home/n/.pyenv/versions/3.6.3/lib/python3.6/http/client.py", line 1331, in getresponse
response.begin()
File "/home/n/.pyenv/versions/3.6.3/lib/python3.6/http/client.py", line 297, in begin
version, status, reason = self._read_status()
File "/home/n/.pyenv/versions/3.6.3/lib/python3.6/http/client.py", line 258, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/home/n/.pyenv/versions/3.6.3/lib/python3.6/socket.py", line 586, in readinto
return self._sock.recv_into(b)
File "/home/n/p/searx/venv3.6/lib/python3.6/site-packages/urllib3/contrib/pyopenssl.py", line 326, in recv_into
raise timeout("The read operation timed out")
socket.timeout: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/n/p/searx/venv3.6/lib/python3.6/site-packages/requests/adapters.py", line 449, in send
timeout=timeout
File "/home/n/p/searx/venv3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 720, in urlopen
method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
File "/home/n/p/searx/venv3.6/lib/python3.6/site-packages/urllib3/util/retry.py", line 400, in increment
raise six.reraise(type(error), error, _stacktrace)
File "/home/n/p/searx/venv3.6/lib/python3.6/site-packages/urllib3/packages/six.py", line 735, in reraise
raise value
File "/home/n/p/searx/venv3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 672, in urlopen
chunked=chunked,
File "/home/n/p/searx/venv3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 423, in _make_request
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
File "/home/n/p/searx/venv3.6/lib/python3.6/site-packages/urllib3/connectionpool.py", line 331, in _raise_timeout
self, url, "Read timed out. (read timeout=%s)" % timeout_value
urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='gitlab.com', port=443): Read timed out. (read timeout=1.0)

During handling of the above exception, another exception occurred:


Traceback (most recent call last):
File "/home/n/p/searx/searx/search.py", line 160, in search_one_http_request_safe
search_results = search_one_http_request(engine, query, request_params)
File "/home/n/p/searx/searx/search.py", line 93, in search_one_http_request
response = send_http_request(engine, request_params)
File "/home/n/p/searx/searx/search.py", line 77, in send_http_request
return req(request_params['url'], **request_args)
File "/home/n/p/searx/searx/poolrequests.py", line 133, in get
return request('get', url, **kwargs)
File "/home/n/p/searx/searx/poolrequests.py", line 109, in request
response = session.request(method=method, url=url, **kwargs)
File "/home/n/p/searx/venv3.6/lib/python3.6/site-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/home/n/p/searx/venv3.6/lib/python3.6/site-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/home/n/p/searx/venv3.6/lib/python3.6/site-packages/requests/adapters.py", line 529, in send
raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='gitlab.com', port=443): Read timed out. (read timeout=1.0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/n/.pyenv/versions/3.6.3/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/home/n/.pyenv/versions/3.6.3/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/home/n/p/searx/searx/search.py", line 107, in search_one_request_safe
return search_one_http_request_safe(engine_name, query, request_params, result_container, start_time, timeout_limit)
File "/home/n/p/searx/searx/search.py", line 189, in search_one_http_request_safe
result_container.add_unresponsive_engine((engine_name, gettext('timeout')))
File "/home/n/p/searx/venv3.6/lib/python3.6/site-packages/flask_babel/__init__.py", line 548, in gettext
t = get_translations()
File "searx/webapp.py", line 168, in _get_translations
translation_locale = request.form.get('use-translation')
File "/home/n/p/searx/venv3.6/lib/python3.6/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/home/n/p/searx/venv3.6/lib/python3.6/site-packages/werkzeug/local.py", line 306, in _get_current_object
return self.__local()
File "/home/n/p/searx/venv3.6/lib/python3.6/site-packages/flask/globals.py", line 37, in _lookup_req_object
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.

# Fixed code
def search_one_offline_request_safe(
    engine_name, query, request_params, result_container, start_time, timeout_limit
):
    engine = engines[engine_name]

    try:
        search_results = search_one_offline_request(engine, query, request_params)

        if search_results:
            result_container.extend(engine_name, search_results)

            engine_time = time() - start_time
            result_container.add_timing(engine_name, engine_time, engine_time)
            with threading.RLock():
                engine.stats["engine_time"] += engine_time
                engine.stats["engine_time_count"] += 1

    except ValueError as e:
        record_offline_engine_stats_on_error(engine, result_container, start_time)
        logger.exception("engine {0} : invalid input : {1}".format(engine_name, e))
    except Exception as e:
        record_offline_engine_stats_on_error(engine, result_container, start_time)
        result_container.add_unresponsive_engine(
            engine_name, "unexpected crash", str(e)
        )
        logger.exception("engine {0} : exception : {1}".format(engine_name, e))