218 lexer = get_lexer_by_name(language, stripall=
True)
220 except Exception
as e:
221 logger.warning(
"pygments lexer: %s " % e)
223 lexer = get_lexer_by_name(
'text', stripall=
True)
228 line_code_start =
None
231 for line, code
in codelines:
233 line_code_start = line
236 if last_line
is not None and last_line + 1 != line:
239 formatter = HtmlFormatter(linenos=
'inline', linenostart=line_code_start, cssclass=
"code-highlight")
240 html_code = html_code + highlight(tmp_code, lexer, formatter)
244 line_code_start = line
247 tmp_code += code +
'\n'
253 formatter = HtmlFormatter(linenos=
'inline', linenostart=line_code_start, cssclass=
"code-highlight")
254 html_code = html_code + highlight(tmp_code, lexer, formatter)
374 kwargs[
'client_settings'] = str(
385 kwargs[
'endpoint'] =
'results' if 'q' in kwargs
else request.endpoint
386 kwargs[
'cookies'] = request.cookies
387 kwargs[
'errors'] = request.errors
388 kwargs[
'link_token'] = link_token.get_token()
391 kwargs[
'preferences'] = request.preferences
392 kwargs[
'autocomplete'] = request.preferences.get_value(
'autocomplete')
393 kwargs[
'favicon_resolver'] = request.preferences.get_value(
'favicon_resolver')
394 kwargs[
'infinite_scroll'] = request.preferences.get_value(
'infinite_scroll')
395 kwargs[
'search_on_category_select'] = request.preferences.get_value(
'search_on_category_select')
396 kwargs[
'hotkeys'] = request.preferences.get_value(
'hotkeys')
397 kwargs[
'results_on_new_tab'] = request.preferences.get_value(
'results_on_new_tab')
398 kwargs[
'advanced_search'] = request.preferences.get_value(
'advanced_search')
399 kwargs[
'query_in_title'] = request.preferences.get_value(
'query_in_title')
400 kwargs[
'safesearch'] = str(request.preferences.get_value(
'safesearch'))
401 kwargs[
'theme'] = request.preferences.get_value(
'theme')
402 kwargs[
'method'] = request.preferences.get_value(
'method')
403 kwargs[
'categories_as_tabs'] = list(settings[
'categories_as_tabs'].keys())
405 kwargs[
'DEFAULT_CATEGORY'] = DEFAULT_CATEGORY
408 kwargs[
'sxng_locales'] = [l
for l
in sxng_locales
if l[0]
in settings[
'search'][
'languages']]
410 locale = request.preferences.get_value(
'locale')
413 if locale
in RTL_LOCALES
and 'rtl' not in kwargs:
416 if 'current_language' not in kwargs:
417 kwargs[
'current_language'] = parse_lang(request.preferences, {},
RawTextQuery(
'', []))
420 kwargs[
'search_formats'] = [x
for x
in settings[
'search'][
'formats']
if x !=
'html']
421 kwargs[
'instance_name'] = get_setting(
'general.instance_name')
422 kwargs[
'searx_version'] = VERSION_STRING
423 kwargs[
'searx_git_url'] = GIT_URL
424 kwargs[
'enable_metrics'] = get_setting(
'general.enable_metrics')
425 kwargs[
'get_setting'] = get_setting
426 kwargs[
'get_pretty_url'] = get_pretty_url
429 donation_url = get_setting(
'general.donation_url')
430 if donation_url
is True:
432 kwargs[
'donation_url'] = donation_url
435 kwargs[
'url_for'] = custom_url_for
436 kwargs[
'image_proxify'] = image_proxify
437 kwargs[
'favicon_url'] = favicons.favicon_url
438 kwargs[
'proxify'] = morty_proxify
if settings[
'result_proxy'][
'url']
is not None else None
439 kwargs[
'proxify_results'] = settings[
'result_proxy'][
'proxify_results']
440 kwargs[
'cache_url'] = settings[
'ui'][
'cache_url']
441 kwargs[
'get_result_template'] = get_result_template
442 kwargs[
'doi_resolver'] = get_doi_resolver(request.preferences)
443 kwargs[
'opensearch_url'] = (
444 url_for(
'opensearch')
448 'method': request.preferences.get_value(
'method'),
449 'autocomplete': request.preferences.get_value(
'autocomplete'),
453 kwargs[
'urlparse'] = urlparse
456 kwargs[
'scripts'] = set()
457 for plugin
in request.user_plugins:
458 for script
in plugin.js_dependencies:
459 kwargs[
'scripts'].add(script)
462 kwargs[
'styles'] = set()
463 for plugin
in request.user_plugins:
464 for css
in plugin.css_dependencies:
465 kwargs[
'styles'].add(css)
467 start_time = default_timer()
468 result = render_template(
'{}/{}'.
format(kwargs[
'theme'], template_name), **kwargs)
469 request.render_time += default_timer() - start_time
476 request.start_time = default_timer()
477 request.render_time = 0
481 client_pref = ClientPref.from_http_request(request)
483 preferences =
Preferences(themes, list(categories.keys()), engines, plugins, client_pref)
485 user_agent = request.headers.get(
'User-Agent',
'').lower()
486 if 'webkit' in user_agent
and 'android' in user_agent:
487 preferences.key_value_settings[
'method'].value =
'GET'
488 request.preferences = preferences
491 preferences.parse_dict(request.cookies)
493 except Exception
as e:
494 logger.exception(e, exc_info=
True)
495 request.errors.append(gettext(
'Invalid settings, please edit your preferences'))
499 request.form = dict(request.form.items())
500 for k, v
in request.args.items():
501 if k
not in request.form:
504 if request.form.get(
'preferences'):
505 preferences.parse_encoded_data(request.form[
'preferences'])
508 preferences.parse_dict(request.form)
509 except Exception
as e:
510 logger.exception(e, exc_info=
True)
511 request.errors.append(gettext(
'Invalid settings'))
515 if not preferences.get_value(
"language"):
517 preferences.parse_dict({
"language": language})
518 logger.debug(
'set language %s (from browser)', preferences.get_value(
"language"))
522 if not preferences.get_value(
"locale"):
524 preferences.parse_dict({
"locale": locale})
525 logger.debug(
'set locale %s (from browser)', preferences.get_value(
"locale"))
528 request.user_plugins = []
529 allowed_plugins = preferences.plugins.get_enabled()
530 disabled_plugins = preferences.plugins.get_disabled()
531 for plugin
in plugins:
532 if (plugin.default_on
and plugin.id
not in disabled_plugins)
or plugin.id
in allowed_plugins:
533 request.user_plugins.append(plugin)
548 total_time = default_timer() - request.start_time
550 'total;dur=' + str(round(total_time * 1000, 3)),
551 'render;dur=' + str(round(request.render_time * 1000, 3)),
553 if len(request.timings) > 0:
554 timings = sorted(request.timings, key=
lambda t: t.total)
556 'total_' + str(i) +
'_' + t.engine +
';dur=' + str(round(t.total * 1000, 3))
for i, t
in enumerate(timings)
559 'load_' + str(i) +
'_' + t.engine +
';dur=' + str(round(t.load * 1000, 3))
560 for i, t
in enumerate(timings)
563 timings_all = timings_all + timings_total + timings_load
564 response.headers.add(
'Server-Timing',
', '.join(timings_all))
628 """Search query in q and return results.
630 Supported outputs: html, json, csv, rss.
636 output_format = request.form.get(
'format',
'html')
637 if output_format
not in OUTPUT_FORMATS:
638 output_format =
'html'
640 if output_format
not in settings[
'search'][
'formats']:
644 if not request.form.get(
'q'):
645 if output_format ==
'html':
649 selected_categories=get_selected_categories(request.preferences, request.form),
656 raw_text_query =
None
657 result_container =
None
659 search_query, raw_text_query, _, _, selected_locale = get_search_query_from_webapp(
660 request.preferences, request.form
663 result_container = search.search()
665 except SearxParameterException
as e:
666 logger.exception(
'search error: SearxParameterException')
668 except Exception
as e:
669 logger.exception(e, exc_info=
True)
670 return index_error(output_format, gettext(
'search error')), 500
673 if result_container.redirect_url:
674 return redirect(result_container.redirect_url)
678 request.timings = result_container.get_timings()
682 if output_format ==
'json':
684 response = webutils.get_json_response(search_query, result_container)
685 return Response(response, mimetype=
'application/json')
687 if output_format ==
'csv':
690 webutils.write_csv_response(csv, result_container)
693 response = Response(csv.stream.read(), mimetype=
'application/csv')
694 cont_disp =
'attachment;Filename=searx_-_{0}.csv'.
format(search_query.query)
695 response.headers.add(
'Content-Disposition', cont_disp)
700 current_template =
None
701 previous_result =
None
703 results = result_container.get_ordered_results()
705 if search_query.redirect_to_first_result
and results:
706 return redirect(results[0][
'url'], 302)
708 for result
in results:
709 if output_format ==
'html':
710 if 'content' in result
and result[
'content']:
711 result[
'content'] = highlight_content(escape(result[
'content'][:1024]), search_query.query)
712 if 'title' in result
and result[
'title']:
713 result[
'title'] = highlight_content(escape(result[
'title']
or ''), search_query.query)
716 result[
'pretty_url'] = webutils.prettify_url(result[
'url'])
717 if result.get(
'publishedDate'):
719 result[
'pubdate'] = result[
'publishedDate'].strftime(
'%Y-%m-%d %H:%M:%S%z')
721 result[
'publishedDate'] =
None
723 result[
'publishedDate'] = webutils.searxng_l10n_timespan(result[
'publishedDate'])
727 if current_template != result.get(
'template'):
728 result[
'open_group'] =
True
730 previous_result[
'close_group'] =
True
731 current_template = result.get(
'template')
732 previous_result = result
735 previous_result[
'close_group'] =
True
739 if output_format ==
'rss':
741 'opensearch_response_rss.xml',
743 answers=result_container.answers,
744 corrections=result_container.corrections,
745 suggestions=result_container.suggestions,
747 number_of_results=result_container.number_of_results,
749 return Response(response_rss, mimetype=
'text/xml')
754 suggestion_urls = list(
756 lambda suggestion: {
'url': raw_text_query.changeQuery(suggestion).getFullQuery(),
'title': suggestion},
757 result_container.suggestions,
761 correction_urls = list(
763 lambda correction: {
'url': raw_text_query.changeQuery(correction).getFullQuery(),
'title': correction},
764 result_container.corrections,
769 engine_timings = sorted(result_container.get_timings(), reverse=
True, key=
lambda e: e.total)
770 max_response_time = engine_timings[0].total
if engine_timings
else None
771 engine_timings_pairs = [(timing.engine, timing.total)
for timing
in engine_timings]
781 selected_categories = search_query.categories,
782 pageno = search_query.pageno,
783 time_range = search_query.time_range
or '',
784 number_of_results = format_decimal(result_container.number_of_results),
785 suggestions = suggestion_urls,
786 answers = result_container.answers,
787 corrections = correction_urls,
788 infoboxes = result_container.infoboxes,
789 engine_data = result_container.engine_data,
790 paging = result_container.paging,
791 unresponsive_engines = webutils.get_translated_errors(
792 result_container.unresponsive_engines
794 current_locale = request.preferences.get_value(
"locale"),
795 current_language = selected_locale,
796 search_language = match_locale(
797 search.search_query.lang,
798 settings[
'search'][
'languages'],
799 fallback=request.preferences.get_value(
"language")
801 timeout_limit = request.form.get(
'timeout_limit',
None),
802 timings = engine_timings_pairs,
803 max_response_time = max_response_time
808@app.route('/about', methods=['GET'])
833 """Return autocompleter results"""
839 disabled_engines = request.preferences.engines.get_disabled()
842 raw_text_query =
RawTextQuery(request.form.get(
'q',
''), disabled_engines)
843 sug_prefix = raw_text_query.getQuery()
847 if len(raw_text_query.autocomplete_list) == 0
and len(sug_prefix) > 0:
850 sxng_locale = request.preferences.get_value(
'language')
851 backend_name = request.preferences.get_value(
'autocomplete')
853 for result
in search_autocomplete(backend_name, sug_prefix, sxng_locale):
856 if result != sug_prefix:
857 results.append(raw_text_query.changeQuery(result).getFullQuery())
859 if len(raw_text_query.autocomplete_list) > 0:
860 for autocomplete_text
in raw_text_query.autocomplete_list:
861 results.append(raw_text_query.get_autocomplete_full_query(autocomplete_text))
863 for answers
in ask(raw_text_query):
864 for answer
in answers:
865 results.append(str(answer[
'answer']))
867 if request.headers.get(
'X-Requested-With') ==
'XMLHttpRequest':
869 suggestions = json.dumps(results)
870 mimetype =
'application/json'
873 suggestions = json.dumps([sug_prefix, results])
874 mimetype =
'application/x-suggestions+json'
876 suggestions = escape(suggestions,
False)
877 return Response(suggestions, mimetype=mimetype)
880@app.route('/preferences', methods=['GET', 'POST'])
882 """Render preferences page && save user preferences"""
888 if request.args.get(
'preferences')
or request.form.get(
'preferences'):
889 resp = make_response(redirect(url_for(
'index', _external=
True)))
890 return request.preferences.save(resp)
893 if request.method ==
'POST':
894 resp = make_response(redirect(url_for(
'index', _external=
True)))
896 request.preferences.parse_form(request.form)
897 except ValidationException:
898 request.errors.append(gettext(
'Invalid settings, please edit your preferences'))
900 return request.preferences.save(resp)
903 image_proxy = request.preferences.get_value(
'image_proxy')
904 disabled_engines = request.preferences.engines.get_disabled()
905 allowed_plugins = request.preferences.plugins.get_enabled()
908 filtered_engines = dict(filter(
lambda kv: request.preferences.validate_token(kv[1]), engines.items()))
910 engines_by_category = {}
913 engines_by_category[c] = [e
for e
in categories[c]
if e.name
in filtered_engines]
915 list.sort(engines_by_category[c], key=
lambda e: e.name)
921 for _, e
in filtered_engines.items():
922 h = histogram(
'engine', e.name,
'time',
'total')
923 median = round(h.percentage(50), 1)
if h.count > 0
else None
924 rate80 = round(h.percentage(80), 1)
if h.count > 0
else None
925 rate95 = round(h.percentage(95), 1)
if h.count > 0
else None
927 max_rate95 = max(max_rate95, rate95
or 0)
929 result_count_sum = histogram(
'engine', e.name,
'result',
'count').sum
930 successful_count = counter(
'engine', e.name,
'search',
'count',
'successful')
931 result_count = int(result_count_sum / float(successful_count))
if successful_count
else 0
937 'warn_timeout': e.timeout > settings[
'outgoing'][
'request_timeout'],
938 'supports_selected_language': e.traits.is_locale_supported(
939 str(request.preferences.get_value(
'language')
or 'all')
941 'result_count': result_count,
947 engine_errors = get_engine_errors(filtered_engines)
948 checker_results = checker_get_result()
950 checker_results[
'engines']
if checker_results[
'status'] ==
'ok' and 'engines' in checker_results
else {}
952 for _, e
in filtered_engines.items():
953 checker_result = checker_results.get(e.name, {})
954 checker_success = checker_result.get(
'success',
True)
955 errors = engine_errors.get(e.name)
or []
956 if counter(
'engine', e.name,
'search',
'count',
'sent') == 0:
959 elif checker_success
and not errors:
961 elif 'simple' in checker_result.get(
'errors', {}):
967 reliability = 100 - sum([error[
'percentage']
for error
in errors
if not error.get(
'secondary')])
969 reliabilities[e.name] = {
970 'reliability': reliability,
972 'checker': checker_results.get(e.name, {}).get(
'errors', {}).keys(),
976 reliabilities_errors = []
978 error_user_text =
None
979 if error.get(
'secondary')
or 'exception_classname' not in error:
981 error_user_text = exception_classname_to_text.get(error.get(
'exception_classname'))
983 error_user_text = exception_classname_to_text[
None]
984 if error_user_text
not in reliabilities_errors:
985 reliabilities_errors.append(error_user_text)
986 reliabilities[e.name][
'errors'] = reliabilities_errors
990 for _, e
in filtered_engines.items():
991 supports_selected_language = e.traits.is_locale_supported(
992 str(request.preferences.get_value(
'language')
or 'all')
994 safesearch = e.safesearch
995 time_range_support = e.time_range_support
996 for checker_test_name
in checker_results.get(e.name, {}).get(
'errors', {}):
997 if supports_selected_language
and checker_test_name.startswith(
'lang_'):
998 supports_selected_language =
'?'
999 elif safesearch
and checker_test_name ==
'safesearch':
1001 elif time_range_support
and checker_test_name ==
'time_range':
1002 time_range_support =
'?'
1003 supports[e.name] = {
1004 'supports_selected_language': supports_selected_language,
1005 'safesearch': safesearch,
1006 'time_range_support': time_range_support,
1012 selected_categories = get_selected_categories(request.preferences, request.form),
1013 locales = LOCALE_NAMES,
1014 current_locale = request.preferences.get_value(
"locale"),
1015 image_proxy = image_proxy,
1016 engines_by_category = engines_by_category,
1018 max_rate95 = max_rate95,
1019 reliabilities = reliabilities,
1020 supports = supports,
1022 {
'info': a.self_info(),
'keywords': a.keywords}
1025 disabled_engines = disabled_engines,
1026 autocomplete_backends = autocomplete_backends,
1027 favicon_resolver_names = favicons.proxy.CFG.resolver_map.keys(),
1028 shortcuts = {y: x
for x, y
in engine_shortcuts.items()},
1031 doi_resolvers = settings[
'doi_resolvers'],
1032 current_doi_resolver = get_doi_resolver(request.preferences),
1033 allowed_plugins = allowed_plugins,
1034 preferences_url_params = request.preferences.get_as_url_params(),
1035 locked_preferences = settings[
'preferences'][
'lock'],
1048 url = request.args.get(
'url')
1052 if not is_hmac_of(settings[
'server'][
'secret_key'], url.encode(), request.args.get(
'h',
'')):
1055 maximum_size = 5 * 1024 * 1024
1056 forward_resp =
False
1060 'User-Agent': gen_useragent(),
1061 'Accept':
'image/webp,*/*',
1062 'Accept-Encoding':
'gzip, deflate',
1066 set_context_network_name(
'image_proxy')
1067 resp, stream = http_stream(method=
'GET', url=url, headers=request_headers, allow_redirects=
True)
1068 content_length = resp.headers.get(
'Content-Length')
1069 if content_length
and content_length.isdigit()
and int(content_length) > maximum_size:
1070 return 'Max size', 400
1072 if resp.status_code != 200:
1073 logger.debug(
'image-proxy: wrong response code: %i', resp.status_code)
1074 if resp.status_code >= 400:
1075 return '', resp.status_code
1078 if not resp.headers.get(
'Content-Type',
'').startswith(
'image/')
and not resp.headers.get(
1080 ).startswith(
'binary/octet-stream'):
1081 logger.debug(
'image-proxy: wrong content-type: %s', resp.headers.get(
'Content-Type',
''))
1085 except httpx.HTTPError:
1086 logger.exception(
'HTTP error')
1089 if resp
and not forward_resp:
1094 except httpx.HTTPError:
1095 logger.exception(
'HTTP error on closing')
1098 nonlocal resp, stream
1104 except httpx.HTTPError
as e:
1105 logger.debug(
'Exception while closing response', e)
1108 headers = dict_subset(resp.headers, {
'Content-Type',
'Content-Encoding',
'Content-Length',
'Length'})
1109 response = Response(stream, mimetype=resp.headers[
'Content-Type'], headers=headers, direct_passthrough=
True)
1110 response.call_on_close(close_stream)
1112 except httpx.HTTPError:
1117@app.route('/engine_descriptions.json', methods=['GET'])
1119 locale = get_locale().split(
'_')[0]
1120 result = ENGINE_DESCRIPTIONS[
'en'].copy()
1122 for engine, description
in ENGINE_DESCRIPTIONS.get(locale, {}).items():
1123 result[engine] = description
1124 for engine, description
in result.items():
1125 if len(description) == 2
and description[1] ==
'ref':
1126 ref_engine, ref_lang = description[0].split(
':')
1127 description = ENGINE_DESCRIPTIONS[ref_lang][ref_engine]
1128 if isinstance(description, str):
1129 description = [description,
'wikipedia']
1130 result[engine] = description
1133 for engine_name, engine_mod
in engines.items():
1134 descr = getattr(engine_mod,
'about', {}).get(
'description',
None)
1135 if descr
is not None:
1136 result[engine_name] = [descr,
"SearXNG config"]
1138 return jsonify(result)
1141@app.route('/stats', methods=['GET'])
1143 """Render engine statistics page."""
1144 sort_order = request.args.get(
'sort', default=
'name', type=str)
1145 selected_engine_name = request.args.get(
'engine', default=
None, type=str)
1147 filtered_engines = dict(filter(
lambda kv: request.preferences.validate_token(kv[1]), engines.items()))
1148 if selected_engine_name:
1149 if selected_engine_name
not in filtered_engines:
1150 selected_engine_name =
None
1152 filtered_engines = [selected_engine_name]
1154 checker_results = checker_get_result()
1156 checker_results[
'engines']
if checker_results[
'status'] ==
'ok' and 'engines' in checker_results
else {}
1159 engine_stats = get_engines_stats(filtered_engines)
1160 engine_reliabilities = get_reliabilities(filtered_engines, checker_results)
1162 if sort_order
not in STATS_SORT_PARAMETERS:
1165 reverse, key_name, default_value = STATS_SORT_PARAMETERS[sort_order]
1167 def get_key(engine_stat):
1168 reliability = engine_reliabilities.get(engine_stat[
'name'], {}).get(
'reliability', 0)
1169 reliability_order = 0
if reliability
else 1
1170 if key_name ==
'reliability':
1172 reliability_order = 0
1174 key = engine_stat.get(key_name)
or default_value
1176 reliability_order = 1 - reliability_order
1177 return (reliability_order, key, engine_stat[
'name'])
1179 technical_report = []
1180 for error
in engine_reliabilities.get(selected_engine_name, {}).get(
'errors', []):
1181 technical_report.append(
1183 Error: {error['exception_classname'] or error['log_message']} \
1184 Parameters: {error['log_parameters']} \
1185 File name: {error['filename'] }:{ error['line_no'] } \
1186 Error Function: {error['function']} \
1187 Code: {error['code']} \
1192 technical_report =
' '.join(technical_report)
1194 engine_stats[
'time'] = sorted(engine_stats[
'time'], reverse=reverse, key=get_key)
1198 sort_order = sort_order,
1199 engine_stats = engine_stats,
1200 engine_reliabilities = engine_reliabilities,
1201 selected_engine_name = selected_engine_name,
1202 searx_git_branch = GIT_BRANCH,
1203 technical_report = technical_report,
1208@app.route('/stats/errors', methods=['GET'])