[refactor] typification of SearXNG (initial) / result items (part 1)

Typification of SearXNG
=======================

This patch introduces the typing of the results.  The why and how is described
in the documentation, please generate the documentation ..

    $ make docs.clean docs.live

and read the following articles in the "Developer documentation":

- result types --> http://0.0.0.0:8000/dev/result_types/index.html

The result types are available from the `searx.result_types` module.  The
following have been implemented so far:

- base result type: `searx.result_type.Result`
  --> http://0.0.0.0:8000/dev/result_types/base_result.html

- answer results
  --> http://0.0.0.0:8000/dev/result_types/answer.html

including the type for translations (inspired by #3925).  For all other
types (which still need to be set up in subsequent PRs), template documentation
has been created for the transition period.

Doc of the fields used in Templates
===================================

The template documentation is the basis for the typing and is the first complete
documentation of the results (needed for engine development).  It is the
"working paper" (the plan) with which further typifications can be implemented
in subsequent PRs.

- https://github.com/searxng/searxng/issues/357

Answer Templates
================

With the new (sub) types for `Answer`, the templates for the answers have also
been revised, `Translation` are now displayed with collapsible entries (inspired
by #3925).

    !en-de dog

Plugins & Answerer
==================

The implementation for `Plugin` and `Answer` has been revised, see
documentation:

- Plugin: http://0.0.0.0:8000/dev/plugins/index.html
- Answerer: http://0.0.0.0:8000/dev/answerers/index.html

With `AnswerStorage` and `AnswerStorage` to manage those items (in follow up
PRs, `ArticleStorage`, `InfoStorage` and .. will be implemented)

Autocomplete
============

The autocompletion had a bug where the results from `Answer` had not been shown
in the past.  To test activate autocompletion and try search terms for which we
have answerers

- statistics: type `min 1 2 3` .. in the completion list you should find an
  entry like `[de] min(1, 2, 3) = 1`

- random: type `random uuid` .. in the completion list, the first item is a
  random UUID

Extended Types
==============

SearXNG extends e.g. the request and response types of flask and httpx, a module
has been set up for type extensions:

- Extended Types
  --> http://0.0.0.0:8000/dev/extended_types.html

Unit-Tests
==========

The unit tests have been completely revised.  In the previous implementation,
the runtime (the global variables such as `searx.settings`) was not initialized
before each test, so the runtime environment with which a test ran was always
determined by the tests that ran before it.  This was also the reason why we
sometimes had to observe non-deterministic errors in the tests in the past:

- https://github.com/searxng/searxng/issues/2988 is one example for the Runtime
  issues, with non-deterministic behavior ..

- https://github.com/searxng/searxng/pull/3650
- https://github.com/searxng/searxng/pull/3654
- https://github.com/searxng/searxng/pull/3642#issuecomment-2226884469
- https://github.com/searxng/searxng/pull/3746#issuecomment-2300965005

Why msgspec.Struct
==================

We have already discussed typing based on e.g. `TypeDict` or `dataclass` in the past:

- https://github.com/searxng/searxng/pull/1562/files
- https://gist.github.com/dalf/972eb05e7a9bee161487132a7de244d2
- https://github.com/searxng/searxng/pull/1412/files
- https://github.com/searxng/searxng/pull/1356

In my opinion, TypeDict is unsuitable because the objects are still dictionaries
and not instances of classes / the `dataclass` are classes but ...

The `msgspec.Struct` combine the advantages of typing, runtime behaviour and
also offer the option of (fast) serializing (incl. type check) the objects.

Currently not possible but conceivable with `msgspec`: Outsourcing the engines
into separate processes, what possibilities this opens up in the future is left
to the imagination!

Internally, we have already defined that it is desirable to decouple the
development of the engines from the development of the SearXNG core / The
serialization of the `Result` objects is a prerequisite for this.

HINT: The threads listed above were the template for this PR, even though the
implementation here is based on msgspec.  They should also be an inspiration for
the following PRs of typification, as the models and implementations can provide
a good direction.

Why just one commit?
====================

I tried to create several (thematically separated) commits, but gave up at some
point ... there are too many things to tackle at once / The comprehensibility of
the commits would not be improved by a thematic separation. On the contrary, we
would have to make multiple changes at the same places and the goal of a change
would be vaguely recognizable in the fog of the commits.

Signed-off-by: Markus Heiser <markus.heiser@darmarit.de>
This commit is contained in:
Markus Heiser
2024-12-15 09:59:50 +01:00
committed by Markus Heiser
parent 9079d0cac0
commit edfbf1e118
143 changed files with 3877 additions and 2118 deletions

View File

@@ -4,6 +4,7 @@
"""
# pylint: disable=use-dict-literal
from __future__ import annotations
import hashlib
import hmac
@@ -16,12 +17,12 @@ from timeit import default_timer
from html import escape
from io import StringIO
import typing
from typing import List, Dict, Iterable
import urllib
import urllib.parse
from urllib.parse import urlencode, urlparse, unquote
import warnings
import httpx
from pygments import highlight
@@ -47,6 +48,7 @@ from flask_babel import (
format_decimal,
)
from searx.extended_types import sxng_request
from searx import (
logger,
get_setting,
@@ -59,7 +61,7 @@ from searx import limiter
from searx.botdetection import link_token
from searx.data import ENGINE_DESCRIPTIONS
from searx.results import Timing
from searx.result_types import Answer
from searx.settings_defaults import OUTPUT_FORMATS
from searx.settings_loader import DEFAULT_SETTINGS_FILE
from searx.exceptions import SearxParameterException
@@ -90,17 +92,16 @@ from searx.webadapter import (
from searx.utils import gen_useragent, dict_subset
from searx.version import VERSION_STRING, GIT_URL, GIT_BRANCH
from searx.query import RawTextQuery
from searx.plugins import Plugin, plugins, initialize as plugin_initialize
from searx.plugins.oa_doi_rewrite import get_doi_resolver
from searx.preferences import (
Preferences,
ClientPref,
ValidationException,
)
from searx.answerers import (
answerers,
ask,
)
import searx.answerers
import searx.plugins
from searx.metrics import get_engines_stats, get_engine_errors, get_reliabilities, histogram, counter, openmetrics
from searx.flaskfix import patch_application
@@ -118,12 +119,15 @@ from searx import favicons
from searx.redisdb import initialize as redis_initialize
from searx.sxng_locales import sxng_locales
from searx.search import SearchWithPlugins, initialize as search_initialize
import searx.search
from searx.network import stream as http_stream, set_context_network_name
from searx.search.checker import get_result as checker_get_result
logger = logger.getChild('webapp')
warnings.simplefilter("always")
# check secret_key
if not searx_debug and settings['server']['secret_key'] == 'ultrasecretkey':
logger.error('server.secret_key is not changed. Please use something else instead of ultrasecretkey.')
@@ -158,24 +162,9 @@ app.jinja_env.filters['group_engines_in_tab'] = group_engines_in_tab # pylint:
app.secret_key = settings['server']['secret_key']
class ExtendedRequest(flask.Request):
"""This class is never initialized and only used for type checking."""
preferences: Preferences
errors: List[str]
user_plugins: List[Plugin]
form: Dict[str, str]
start_time: float
render_time: float
timings: List[Timing]
request = typing.cast(ExtendedRequest, flask.request)
def get_locale():
locale = localeselector()
logger.debug("%s uses locale `%s`", urllib.parse.quote(request.url), locale)
logger.debug("%s uses locale `%s`", urllib.parse.quote(sxng_request.url), locale)
return locale
@@ -260,7 +249,7 @@ def custom_url_for(endpoint: str, **values):
file_hash = static_files.get(values['filename'])
if not file_hash:
# try file in the current theme
theme_name = request.preferences.get_value('theme')
theme_name = sxng_request.preferences.get_value('theme')
filename_with_theme = "themes/{}/{}".format(theme_name, values['filename'])
file_hash = static_files.get(filename_with_theme)
if file_hash:
@@ -268,7 +257,7 @@ def custom_url_for(endpoint: str, **values):
if get_setting('ui.static_use_hash') and file_hash:
suffix = "?" + file_hash
if endpoint == 'info' and 'locale' not in values:
locale = request.preferences.get_value('locale')
locale = sxng_request.preferences.get_value('locale')
if infopage.INFO_PAGES.get_page(values['pagename'], locale) is None:
locale = infopage.INFO_PAGES.locale_default
values['locale'] = locale
@@ -295,7 +284,7 @@ def image_proxify(url: str):
if url.startswith('//'):
url = 'https:' + url
if not request.preferences.get_value('image_proxy'):
if not sxng_request.preferences.get_value('image_proxy'):
return url
if url.startswith('data:image/'):
@@ -328,11 +317,11 @@ def get_translations():
}
def get_enabled_categories(category_names: Iterable[str]):
def get_enabled_categories(category_names: typing.Iterable[str]):
"""The categories in ``category_names```for which there is no active engine
are filtered out and a reduced list is returned."""
enabled_engines = [item[0] for item in request.preferences.engines.get_enabled()]
enabled_engines = [item[0] for item in sxng_request.preferences.engines.get_enabled()]
enabled_categories = set()
for engine_name in enabled_engines:
enabled_categories.update(engines[engine_name].categories)
@@ -340,7 +329,7 @@ def get_enabled_categories(category_names: Iterable[str]):
def get_pretty_url(parsed_url: urllib.parse.ParseResult):
url_formatting_pref = request.preferences.get_value('url_formatting')
url_formatting_pref = sxng_request.preferences.get_value('url_formatting')
if url_formatting_pref == 'full':
return [parsed_url.geturl()]
@@ -355,7 +344,7 @@ def get_pretty_url(parsed_url: urllib.parse.ParseResult):
def get_client_settings():
req_pref = request.preferences
req_pref = sxng_request.preferences
return {
'autocomplete': req_pref.get_value('autocomplete'),
'autocomplete_min': get_setting('search.autocomplete_min'),
@@ -389,13 +378,13 @@ def render(template_name: str, **kwargs):
),
encoding='utf-8',
)
kwargs['preferences'] = request.preferences
kwargs['preferences'] = sxng_request.preferences
kwargs.update(client_settings)
# values from the HTTP requests
kwargs['endpoint'] = 'results' if 'q' in kwargs else request.endpoint
kwargs['cookies'] = request.cookies
kwargs['errors'] = request.errors
kwargs['endpoint'] = 'results' if 'q' in kwargs else sxng_request.endpoint
kwargs['cookies'] = sxng_request.cookies
kwargs['errors'] = sxng_request.errors
kwargs['link_token'] = link_token.get_token()
kwargs['categories_as_tabs'] = list(settings['categories_as_tabs'].keys())
@@ -405,14 +394,14 @@ def render(template_name: str, **kwargs):
# i18n
kwargs['sxng_locales'] = [l for l in sxng_locales if l[0] in settings['search']['languages']]
locale = request.preferences.get_value('locale')
locale = sxng_request.preferences.get_value('locale')
kwargs['locale_rfc5646'] = _get_locale_rfc5646(locale)
if locale in RTL_LOCALES and 'rtl' not in kwargs:
kwargs['rtl'] = True
if 'current_language' not in kwargs:
kwargs['current_language'] = parse_lang(request.preferences, {}, RawTextQuery('', []))
kwargs['current_language'] = parse_lang(sxng_request.preferences, {}, RawTextQuery('', []))
# values from settings
kwargs['search_formats'] = [x for x in settings['search']['formats'] if x != 'html']
@@ -442,92 +431,80 @@ def render(template_name: str, **kwargs):
+ '?'
+ urlencode(
{
'method': request.preferences.get_value('method'),
'autocomplete': request.preferences.get_value('autocomplete'),
'method': sxng_request.preferences.get_value('method'),
'autocomplete': sxng_request.preferences.get_value('autocomplete'),
}
)
)
kwargs['urlparse'] = urlparse
# scripts from plugins
kwargs['scripts'] = set()
for plugin in request.user_plugins:
for script in plugin.js_dependencies:
kwargs['scripts'].add(script)
# styles from plugins
kwargs['styles'] = set()
for plugin in request.user_plugins:
for css in plugin.css_dependencies:
kwargs['styles'].add(css)
start_time = default_timer()
result = render_template('{}/{}'.format(kwargs['theme'], template_name), **kwargs)
request.render_time += default_timer() - start_time # pylint: disable=assigning-non-slot
sxng_request.render_time += default_timer() - start_time # pylint: disable=assigning-non-slot
return result
@app.before_request
def pre_request():
request.start_time = default_timer() # pylint: disable=assigning-non-slot
request.render_time = 0 # pylint: disable=assigning-non-slot
request.timings = [] # pylint: disable=assigning-non-slot
request.errors = [] # pylint: disable=assigning-non-slot
sxng_request.start_time = default_timer() # pylint: disable=assigning-non-slot
sxng_request.render_time = 0 # pylint: disable=assigning-non-slot
sxng_request.timings = [] # pylint: disable=assigning-non-slot
sxng_request.errors = [] # pylint: disable=assigning-non-slot
client_pref = ClientPref.from_http_request(request)
client_pref = ClientPref.from_http_request(sxng_request)
# pylint: disable=redefined-outer-name
preferences = Preferences(themes, list(categories.keys()), engines, plugins, client_pref)
preferences = Preferences(themes, list(categories.keys()), engines, searx.plugins.STORAGE, client_pref)
user_agent = request.headers.get('User-Agent', '').lower()
user_agent = sxng_request.headers.get('User-Agent', '').lower()
if 'webkit' in user_agent and 'android' in user_agent:
preferences.key_value_settings['method'].value = 'GET'
request.preferences = preferences # pylint: disable=assigning-non-slot
sxng_request.preferences = preferences # pylint: disable=assigning-non-slot
try:
preferences.parse_dict(request.cookies)
preferences.parse_dict(sxng_request.cookies)
except Exception as e: # pylint: disable=broad-except
logger.exception(e, exc_info=True)
request.errors.append(gettext('Invalid settings, please edit your preferences'))
sxng_request.errors.append(gettext('Invalid settings, please edit your preferences'))
# merge GET, POST vars
# request.form
request.form = dict(request.form.items()) # pylint: disable=assigning-non-slot
for k, v in request.args.items():
if k not in request.form:
request.form[k] = v
# HINT request.form is of type werkzeug.datastructures.ImmutableMultiDict
sxng_request.form = dict(sxng_request.form.items()) # type: ignore
for k, v in sxng_request.args.items():
if k not in sxng_request.form:
sxng_request.form[k] = v
if request.form.get('preferences'):
preferences.parse_encoded_data(request.form['preferences'])
if sxng_request.form.get('preferences'):
preferences.parse_encoded_data(sxng_request.form['preferences'])
else:
try:
preferences.parse_dict(request.form)
preferences.parse_dict(sxng_request.form)
except Exception as e: # pylint: disable=broad-except
logger.exception(e, exc_info=True)
request.errors.append(gettext('Invalid settings'))
sxng_request.errors.append(gettext('Invalid settings'))
# language is defined neither in settings nor in preferences
# use browser headers
if not preferences.get_value("language"):
language = _get_browser_language(request, settings['search']['languages'])
language = _get_browser_language(sxng_request, settings['search']['languages'])
preferences.parse_dict({"language": language})
logger.debug('set language %s (from browser)', preferences.get_value("language"))
# UI locale is defined neither in settings nor in preferences
# use browser headers
if not preferences.get_value("locale"):
locale = _get_browser_language(request, LOCALE_NAMES.keys())
locale = _get_browser_language(sxng_request, LOCALE_NAMES.keys())
preferences.parse_dict({"locale": locale})
logger.debug('set locale %s (from browser)', preferences.get_value("locale"))
# request.user_plugins
request.user_plugins = [] # pylint: disable=assigning-non-slot
sxng_request.user_plugins = [] # pylint: disable=assigning-non-slot
allowed_plugins = preferences.plugins.get_enabled()
disabled_plugins = preferences.plugins.get_disabled()
for plugin in plugins:
if (plugin.default_on and plugin.id not in disabled_plugins) or plugin.id in allowed_plugins:
request.user_plugins.append(plugin)
for plugin in searx.plugins.STORAGE:
if (plugin.id not in disabled_plugins) or plugin.id in allowed_plugins:
sxng_request.user_plugins.append(plugin.id)
@app.after_request
@@ -542,13 +519,13 @@ def add_default_headers(response: flask.Response):
@app.after_request
def post_request(response: flask.Response):
total_time = default_timer() - request.start_time
total_time = default_timer() - sxng_request.start_time
timings_all = [
'total;dur=' + str(round(total_time * 1000, 3)),
'render;dur=' + str(round(request.render_time * 1000, 3)),
'render;dur=' + str(round(sxng_request.render_time * 1000, 3)),
]
if len(request.timings) > 0:
timings = sorted(request.timings, key=lambda t: t.total)
if len(sxng_request.timings) > 0:
timings = sorted(sxng_request.timings, key=lambda t: t.total)
timings_total = [
'total_' + str(i) + '_' + t.engine + ';dur=' + str(round(t.total * 1000, 3)) for i, t in enumerate(timings)
]
@@ -575,18 +552,18 @@ def index_error(output_format: str, error_message: str):
response_rss = render(
'opensearch_response_rss.xml',
results=[],
q=request.form['q'] if 'q' in request.form else '',
q=sxng_request.form['q'] if 'q' in sxng_request.form else '',
number_of_results=0,
error_message=error_message,
)
return Response(response_rss, mimetype='text/xml')
# html
request.errors.append(gettext('search error'))
sxng_request.errors.append(gettext('search error'))
return render(
# fmt: off
'index.html',
selected_categories=get_selected_categories(request.preferences, request.form),
selected_categories=get_selected_categories(sxng_request.preferences, sxng_request.form),
# fmt: on
)
@@ -596,15 +573,15 @@ def index():
"""Render index page."""
# redirect to search if there's a query in the request
if request.form.get('q'):
query = ('?' + request.query_string.decode()) if request.query_string else ''
if sxng_request.form.get('q'):
query = ('?' + sxng_request.query_string.decode()) if sxng_request.query_string else ''
return redirect(url_for('search') + query, 308)
return render(
# fmt: off
'index.html',
selected_categories=get_selected_categories(request.preferences, request.form),
current_locale = request.preferences.get_value("locale"),
selected_categories=get_selected_categories(sxng_request.preferences, sxng_request.form),
current_locale = sxng_request.preferences.get_value("locale"),
# fmt: on
)
@@ -616,14 +593,14 @@ def health():
@app.route('/client<token>.css', methods=['GET', 'POST'])
def client_token(token=None):
link_token.ping(request, token)
link_token.ping(sxng_request, token)
return Response('', mimetype='text/css')
@app.route('/rss.xsl', methods=['GET', 'POST'])
def rss_xsl():
return render_template(
f"{request.preferences.get_value('theme')}/rss.xsl",
f"{sxng_request.preferences.get_value('theme')}/rss.xsl",
url_for=custom_url_for,
)
@@ -638,7 +615,7 @@ def search():
# pylint: disable=too-many-statements
# output_format
output_format = request.form.get('format', 'html')
output_format = sxng_request.form.get('format', 'html')
if output_format not in OUTPUT_FORMATS:
output_format = 'html'
@@ -646,12 +623,12 @@ def search():
flask.abort(403)
# check if there is query (not None and not an empty string)
if not request.form.get('q'):
if not sxng_request.form.get('q'):
if output_format == 'html':
return render(
# fmt: off
'index.html',
selected_categories=get_selected_categories(request.preferences, request.form),
selected_categories=get_selected_categories(sxng_request.preferences, sxng_request.form),
# fmt: on
)
return index_error(output_format, 'No query'), 400
@@ -662,10 +639,10 @@ def search():
result_container = None
try:
search_query, raw_text_query, _, _, selected_locale = get_search_query_from_webapp(
request.preferences, request.form
sxng_request.preferences, sxng_request.form
)
search = SearchWithPlugins(search_query, request.user_plugins, request) # pylint: disable=redefined-outer-name
result_container = search.search()
search_obj = searx.search.SearchWithPlugins(search_query, sxng_request, sxng_request.user_plugins)
result_container = search_obj.search()
except SearxParameterException as e:
logger.exception('search error: SearxParameterException')
@@ -680,7 +657,7 @@ def search():
# 2. add Server-Timing header for measuring performance characteristics of
# web applications
request.timings = result_container.get_timings() # pylint: disable=assigning-non-slot
sxng_request.timings = result_container.get_timings() # pylint: disable=assigning-non-slot
# 3. formats without a template
@@ -745,7 +722,7 @@ def search():
response_rss = render(
'opensearch_response_rss.xml',
results=results,
q=request.form['q'],
q=sxng_request.form['q'],
number_of_results=result_container.number_of_results,
)
return Response(response_rss, mimetype='text/xml')
@@ -779,7 +756,7 @@ def search():
# fmt: off
'results.html',
results = results,
q=request.form['q'],
q=sxng_request.form['q'],
selected_categories = search_query.categories,
pageno = search_query.pageno,
time_range = search_query.time_range or '',
@@ -793,14 +770,14 @@ def search():
unresponsive_engines = webutils.get_translated_errors(
result_container.unresponsive_engines
),
current_locale = request.preferences.get_value("locale"),
current_locale = sxng_request.preferences.get_value("locale"),
current_language = selected_locale,
search_language = match_locale(
search.search_query.lang,
search_obj.search_query.lang,
settings['search']['languages'],
fallback=request.preferences.get_value("language")
fallback=sxng_request.preferences.get_value("language")
),
timeout_limit = request.form.get('timeout_limit', None),
timeout_limit = sxng_request.form.get('timeout_limit', None),
timings = engine_timings_pairs,
max_response_time = max_response_time
# fmt: on
@@ -821,7 +798,7 @@ def info(pagename, locale):
if page is None:
flask.abort(404)
user_locale = request.preferences.get_value('locale')
user_locale = sxng_request.preferences.get_value('locale')
return render(
'info.html',
all_pages=infopage.INFO_PAGES.iter_pages(user_locale, fallback_to_default=True),
@@ -838,19 +815,23 @@ def autocompleter():
results = []
# set blocked engines
disabled_engines = request.preferences.engines.get_disabled()
disabled_engines = sxng_request.preferences.engines.get_disabled()
# parse query
raw_text_query = RawTextQuery(request.form.get('q', ''), disabled_engines)
raw_text_query = RawTextQuery(sxng_request.form.get('q', ''), disabled_engines)
sug_prefix = raw_text_query.getQuery()
for obj in searx.answerers.STORAGE.ask(sug_prefix):
if isinstance(obj, Answer):
results.append(obj.answer)
# normal autocompletion results only appear if no inner results returned
# and there is a query part
if len(raw_text_query.autocomplete_list) == 0 and len(sug_prefix) > 0:
# get SearXNG's locale and autocomplete backend from cookie
sxng_locale = request.preferences.get_value('language')
backend_name = request.preferences.get_value('autocomplete')
sxng_locale = sxng_request.preferences.get_value('language')
backend_name = sxng_request.preferences.get_value('autocomplete')
for result in search_autocomplete(backend_name, sug_prefix, sxng_locale):
# attention: this loop will change raw_text_query object and this is
@@ -862,11 +843,7 @@ def autocompleter():
for autocomplete_text in raw_text_query.autocomplete_list:
results.append(raw_text_query.get_autocomplete_full_query(autocomplete_text))
for answers in ask(raw_text_query):
for answer in answers:
results.append(str(answer['answer']))
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
if sxng_request.headers.get('X-Requested-With') == 'XMLHttpRequest':
# the suggestion request comes from the searx search form
suggestions = json.dumps(results)
mimetype = 'application/json'
@@ -887,27 +864,27 @@ def preferences():
# pylint: disable=too-many-statements
# save preferences using the link the /preferences?preferences=...
if request.args.get('preferences') or request.form.get('preferences'):
if sxng_request.args.get('preferences') or sxng_request.form.get('preferences'):
resp = make_response(redirect(url_for('index', _external=True)))
return request.preferences.save(resp)
return sxng_request.preferences.save(resp)
# save preferences
if request.method == 'POST':
if sxng_request.method == 'POST':
resp = make_response(redirect(url_for('index', _external=True)))
try:
request.preferences.parse_form(request.form)
sxng_request.preferences.parse_form(sxng_request.form)
except ValidationException:
request.errors.append(gettext('Invalid settings, please edit your preferences'))
sxng_request.errors.append(gettext('Invalid settings, please edit your preferences'))
return resp
return request.preferences.save(resp)
return sxng_request.preferences.save(resp)
# render preferences
image_proxy = request.preferences.get_value('image_proxy') # pylint: disable=redefined-outer-name
disabled_engines = request.preferences.engines.get_disabled()
allowed_plugins = request.preferences.plugins.get_enabled()
image_proxy = sxng_request.preferences.get_value('image_proxy') # pylint: disable=redefined-outer-name
disabled_engines = sxng_request.preferences.engines.get_disabled()
allowed_plugins = sxng_request.preferences.plugins.get_enabled()
# stats for preferences page
filtered_engines = dict(filter(lambda kv: request.preferences.validate_token(kv[1]), engines.items()))
filtered_engines = dict(filter(lambda kv: sxng_request.preferences.validate_token(kv[1]), engines.items()))
engines_by_category = {}
@@ -938,7 +915,7 @@ def preferences():
'rate95': rate95,
'warn_timeout': e.timeout > settings['outgoing']['request_timeout'],
'supports_selected_language': e.traits.is_locale_supported(
str(request.preferences.get_value('language') or 'all')
str(sxng_request.preferences.get_value('language') or 'all')
),
'result_count': result_count,
}
@@ -991,7 +968,7 @@ def preferences():
supports = {}
for _, e in filtered_engines.items():
supports_selected_language = e.traits.is_locale_supported(
str(request.preferences.get_value('language') or 'all')
str(sxng_request.preferences.get_value('language') or 'all')
)
safesearch = e.safesearch
time_range_support = e.time_range_support
@@ -1011,31 +988,28 @@ def preferences():
return render(
# fmt: off
'preferences.html',
selected_categories = get_selected_categories(request.preferences, request.form),
preferences = True,
selected_categories = get_selected_categories(sxng_request.preferences, sxng_request.form),
locales = LOCALE_NAMES,
current_locale = request.preferences.get_value("locale"),
current_locale = sxng_request.preferences.get_value("locale"),
image_proxy = image_proxy,
engines_by_category = engines_by_category,
stats = stats,
max_rate95 = max_rate95,
reliabilities = reliabilities,
supports = supports,
answerers = [
{'info': a.self_info(), 'keywords': a.keywords}
for a in answerers
],
answer_storage = searx.answerers.STORAGE.info,
disabled_engines = disabled_engines,
autocomplete_backends = autocomplete_backends,
favicon_resolver_names = favicons.proxy.CFG.resolver_map.keys(),
shortcuts = {y: x for x, y in engine_shortcuts.items()},
themes = themes,
plugins = plugins,
doi_resolvers = settings['doi_resolvers'],
current_doi_resolver = get_doi_resolver(request.preferences),
plugins_storage = searx.plugins.STORAGE.info,
current_doi_resolver = get_doi_resolver(sxng_request.preferences),
allowed_plugins = allowed_plugins,
preferences_url_params = request.preferences.get_as_url_params(),
locked_preferences = settings['preferences']['lock'],
preferences = True
preferences_url_params = sxng_request.preferences.get_as_url_params(),
locked_preferences = get_setting("preferences.lock", []),
doi_resolvers = get_setting("doi_resolvers", {}),
# fmt: on
)
@@ -1047,11 +1021,11 @@ app.add_url_rule('/favicon_proxy', methods=['GET'], endpoint="favicon_proxy", vi
def image_proxy():
# pylint: disable=too-many-return-statements, too-many-branches
url = request.args.get('url')
url = sxng_request.args.get('url')
if not url:
return '', 400
if not is_hmac_of(settings['server']['secret_key'], url.encode(), request.args.get('h', '')):
if not is_hmac_of(settings['server']['secret_key'], url.encode(), sxng_request.args.get('h', '')):
return '', 400
maximum_size = 5 * 1024 * 1024
@@ -1143,10 +1117,10 @@ def engine_descriptions():
@app.route('/stats', methods=['GET'])
def stats():
"""Render engine statistics page."""
sort_order = request.args.get('sort', default='name', type=str)
selected_engine_name = request.args.get('engine', default=None, type=str)
sort_order = sxng_request.args.get('sort', default='name', type=str)
selected_engine_name = sxng_request.args.get('engine', default=None, type=str)
filtered_engines = dict(filter(lambda kv: request.preferences.validate_token(kv[1]), engines.items()))
filtered_engines = dict(filter(lambda kv: sxng_request.preferences.validate_token(kv[1]), engines.items()))
if selected_engine_name:
if selected_engine_name not in filtered_engines:
selected_engine_name = None
@@ -1209,7 +1183,7 @@ def stats():
@app.route('/stats/errors', methods=['GET'])
def stats_errors():
filtered_engines = dict(filter(lambda kv: request.preferences.validate_token(kv[1]), engines.items()))
filtered_engines = dict(filter(lambda kv: sxng_request.preferences.validate_token(kv[1]), engines.items()))
result = get_engine_errors(filtered_engines)
return jsonify(result)
@@ -1227,10 +1201,10 @@ def stats_open_metrics():
if not (settings['general'].get("enable_metrics") and password):
return Response('open metrics is disabled', status=404, mimetype='text/plain')
if not request.authorization or request.authorization.password != password:
if not sxng_request.authorization or sxng_request.authorization.password != password:
return Response('access forbidden', status=401, mimetype='text/plain')
filtered_engines = dict(filter(lambda kv: request.preferences.validate_token(kv[1]), engines.items()))
filtered_engines = dict(filter(lambda kv: sxng_request.preferences.validate_token(kv[1]), engines.items()))
checker_results = checker_get_result()
checker_results = (
@@ -1260,11 +1234,11 @@ Disallow: /*?*q=*
@app.route('/opensearch.xml', methods=['GET'])
def opensearch():
method = request.preferences.get_value('method')
autocomplete = request.preferences.get_value('autocomplete')
method = sxng_request.preferences.get_value('method')
autocomplete = sxng_request.preferences.get_value('autocomplete')
# chrome/chromium only supports HTTP GET....
if request.headers.get('User-Agent', '').lower().find('webkit') >= 0:
if sxng_request.headers.get('User-Agent', '').lower().find('webkit') >= 0:
method = 'GET'
if method not in ('POST', 'GET'):
@@ -1277,9 +1251,9 @@ def opensearch():
@app.route('/favicon.ico')
def favicon():
theme = request.preferences.get_value("theme")
theme = sxng_request.preferences.get_value("theme")
return send_from_directory(
os.path.join(app.root_path, settings['ui']['static_path'], 'themes', theme, 'img'), # pyright: ignore
os.path.join(app.root_path, settings['ui']['static_path'], 'themes', theme, 'img'), # type: ignore
'favicon.png',
mimetype='image/vnd.microsoft.icon',
)
@@ -1288,7 +1262,7 @@ def favicon():
@app.route('/clear_cookies')
def clear_cookies():
resp = make_response(redirect(url_for('index', _external=True)))
for cookie_name in request.cookies:
for cookie_name in sxng_request.cookies:
resp.delete_cookie(cookie_name)
return resp
@@ -1298,7 +1272,7 @@ def config():
"""Return configuration in JSON format."""
_engines = []
for name, engine in engines.items():
if not request.preferences.validate_token(engine):
if not sxng_request.preferences.validate_token(engine):
continue
_languages = engine.traits.languages.keys()
@@ -1319,8 +1293,8 @@ def config():
)
_plugins = []
for _ in plugins:
_plugins.append({'name': _.name, 'enabled': _.default_on})
for _ in searx.plugins.STORAGE:
_plugins.append({'name': _.id, 'enabled': _.default_on})
_limiter_cfg = limiter.get_cfg()
@@ -1375,8 +1349,12 @@ werkzeug_reloader = flask_run_development or (searx_debug and __name__ == "__mai
if not werkzeug_reloader or (werkzeug_reloader and os.environ.get("WERKZEUG_RUN_MAIN") == "true"):
locales_initialize()
redis_initialize()
plugin_initialize(app)
search_initialize(enable_checker=True, check_network=True, enable_metrics=settings['general']['enable_metrics'])
searx.plugins.initialize(app)
searx.search.initialize(
enable_checker=True,
check_network=True,
enable_metrics=get_setting("general.enable_metrics"),
)
limiter.initialize(app, settings)
favicons.init()