# Buggy code
def search_one_http_request_safe(
    engine_name, query, request_params, result_container, start_time, timeout_limit
):
    # set timeout for all HTTP requests
    requests_lib.set_timeout_for_thread(timeout_limit, start_time=start_time)
    # reset the HTTP total time
    requests_lib.reset_time_for_thread()

    #
    engine = engines[engine_name]

    # suppose everything will be alright
    requests_exception = False

    try:
        # send requests and parse the results
        search_results = search_one_http_request(engine, query, request_params)

        # check if the engine accepted the request
        if search_results is not None:
            # yes, so add results
            result_container.extend(engine_name, search_results)

            # update engine time when there is no exception
            engine_time = time() - start_time
            page_load_time = requests_lib.get_time_for_thread()
            result_container.add_timing(engine_name, engine_time, page_load_time)
            with threading.RLock():
                engine.stats["engine_time"] += engine_time
                engine.stats["engine_time_count"] += 1
                # update stats with the total HTTP time
                engine.stats["page_load_time"] += page_load_time
                engine.stats["page_load_count"] += 1

    except Exception as e:
        # Timing
        engine_time = time() - start_time
        page_load_time = requests_lib.get_time_for_thread()
        result_container.add_timing(engine_name, engine_time, page_load_time)

        # Record the errors
        with threading.RLock():
            engine.stats["errors"] += 1

        if issubclass(e.__class__, requests.exceptions.Timeout):
            result_container.add_unresponsive_engine((engine_name, gettext("timeout")))
            # requests timeout (connect or read)
            logger.error(
                "engine {0} : HTTP requests timeout"
                "(search duration : {1} s, timeout: {2} s) : {3}".format(
                    engine_name, engine_time, timeout_limit, e.__class__.__name__
                )
            )
            requests_exception = True
        elif issubclass(e.__class__, requests.exceptions.RequestException):
            result_container.add_unresponsive_engine(
                (engine_name, gettext("request exception"))
            )
            # other requests exception
            logger.exception(
                "engine {0} : requests exception"
                "(search duration : {1} s, timeout: {2} s) : {3}".format(
                    engine_name, engine_time, timeout_limit, e
                )
            )
            requests_exception = True
        else:
            result_container.add_unresponsive_engine(
                (
                    engine_name,
                    "{0}: {1}".format(gettext("unexpected crash"), e),
                )
            )
            # others errors
            logger.exception("engine {0} : exception : {1}".format(engine_name, e))

    # suspend or not the engine if there are HTTP errors
    with threading.RLock():
        if requests_exception:
            # update continuous_errors / suspend_end_time
            engine.continuous_errors += 1
            engine.suspend_end_time = time() + min(
                settings["search"]["max_ban_time_on_fail"],
                engine.continuous_errors * settings["search"]["ban_time_on_fail"],
            )
        else:
            # no HTTP error (perhaps an engine error)
            # anyway, reset the suspend variables
            engine.continuous_errors = 0
            engine.suspend_end_time = 0


# 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_http_request_safe(
    engine_name, query, request_params, result_container, start_time, timeout_limit
):
    # set timeout for all HTTP requests
    requests_lib.set_timeout_for_thread(timeout_limit, start_time=start_time)
    # reset the HTTP total time
    requests_lib.reset_time_for_thread()

    #
    engine = engines[engine_name]

    # suppose everything will be alright
    requests_exception = False

    try:
        # send requests and parse the results
        search_results = search_one_http_request(engine, query, request_params)

        # check if the engine accepted the request
        if search_results is not None:
            # yes, so add results
            result_container.extend(engine_name, search_results)

            # update engine time when there is no exception
            engine_time = time() - start_time
            page_load_time = requests_lib.get_time_for_thread()
            result_container.add_timing(engine_name, engine_time, page_load_time)
            with threading.RLock():
                engine.stats["engine_time"] += engine_time
                engine.stats["engine_time_count"] += 1
                # update stats with the total HTTP time
                engine.stats["page_load_time"] += page_load_time
                engine.stats["page_load_count"] += 1

    except Exception as e:
        # Timing
        engine_time = time() - start_time
        page_load_time = requests_lib.get_time_for_thread()
        result_container.add_timing(engine_name, engine_time, page_load_time)

        # Record the errors
        with threading.RLock():
            engine.stats["errors"] += 1

        if issubclass(e.__class__, requests.exceptions.Timeout):
            result_container.add_unresponsive_engine(engine_name, "timeout")
            # requests timeout (connect or read)
            logger.error(
                "engine {0} : HTTP requests timeout"
                "(search duration : {1} s, timeout: {2} s) : {3}".format(
                    engine_name, engine_time, timeout_limit, e.__class__.__name__
                )
            )
            requests_exception = True
        elif issubclass(e.__class__, requests.exceptions.RequestException):
            result_container.add_unresponsive_engine(engine_name, "request exception")
            # other requests exception
            logger.exception(
                "engine {0} : requests exception"
                "(search duration : {1} s, timeout: {2} s) : {3}".format(
                    engine_name, engine_time, timeout_limit, e
                )
            )
            requests_exception = True
        else:
            result_container.add_unresponsive_engine(
                engine_name, "unexpected crash", str(e)
            )
            # others errors
            logger.exception("engine {0} : exception : {1}".format(engine_name, e))

    # suspend or not the engine if there are HTTP errors
    with threading.RLock():
        if requests_exception:
            # update continuous_errors / suspend_end_time
            engine.continuous_errors += 1
            engine.suspend_end_time = time() + min(
                settings["search"]["max_ban_time_on_fail"],
                engine.continuous_errors * settings["search"]["ban_time_on_fail"],
            )
        else:
            # no HTTP error (perhaps an engine error)
            # anyway, reset the suspend variables
            engine.continuous_errors = 0
            engine.suspend_end_time = 0