209 lexer = get_lexer_by_name(language, stripall=
True)
211 except Exception
as e:
212 logger.warning(
"pygments lexer: %s " % e)
214 lexer = get_lexer_by_name(
'text', stripall=
True)
219 line_code_start =
None
222 for line, code
in codelines:
224 line_code_start = line
227 if last_line
is not None and last_line + 1 != line:
230 formatter = HtmlFormatter(linenos=
'inline', linenostart=line_code_start, cssclass=
"code-highlight")
231 html_code = html_code + highlight(tmp_code, lexer, formatter)
235 line_code_start = line
238 tmp_code += code +
'\n'
244 formatter = HtmlFormatter(linenos=
'inline', linenostart=line_code_start, cssclass=
"code-highlight")
245 html_code = html_code + highlight(tmp_code, lexer, formatter)
383 kwargs[
'client_settings'] = str(
386 json.dumps(client_settings),
392 kwargs[
'preferences'] = request.preferences
393 kwargs.update(client_settings)
396 kwargs[
'endpoint'] =
'results' if 'q' in kwargs
else request.endpoint
397 kwargs[
'cookies'] = request.cookies
398 kwargs[
'errors'] = request.errors
399 kwargs[
'link_token'] = link_token.get_token()
401 kwargs[
'categories_as_tabs'] = list(settings[
'categories_as_tabs'].keys())
403 kwargs[
'DEFAULT_CATEGORY'] = DEFAULT_CATEGORY
406 kwargs[
'sxng_locales'] = [l
for l
in sxng_locales
if l[0]
in settings[
'search'][
'languages']]
408 locale = request.preferences.get_value(
'locale')
411 if locale
in RTL_LOCALES
and 'rtl' not in kwargs:
414 if 'current_language' not in kwargs:
415 kwargs[
'current_language'] = parse_lang(request.preferences, {},
RawTextQuery(
'', []))
418 kwargs[
'search_formats'] = [x
for x
in settings[
'search'][
'formats']
if x !=
'html']
419 kwargs[
'instance_name'] = get_setting(
'general.instance_name')
420 kwargs[
'searx_version'] = VERSION_STRING
421 kwargs[
'searx_git_url'] = GIT_URL
422 kwargs[
'enable_metrics'] = get_setting(
'general.enable_metrics')
423 kwargs[
'get_setting'] = get_setting
424 kwargs[
'get_pretty_url'] = get_pretty_url
427 donation_url = get_setting(
'general.donation_url')
428 if donation_url
is True:
430 kwargs[
'donation_url'] = donation_url
433 kwargs[
'url_for'] = custom_url_for
434 kwargs[
'image_proxify'] = image_proxify
435 kwargs[
'favicon_url'] = favicons.favicon_url
436 kwargs[
'proxify'] = morty_proxify
if settings[
'result_proxy'][
'url']
is not None else None
437 kwargs[
'proxify_results'] = settings[
'result_proxy'][
'proxify_results']
438 kwargs[
'cache_url'] = settings[
'ui'][
'cache_url']
439 kwargs[
'get_result_template'] = get_result_template
440 kwargs[
'opensearch_url'] = (
441 url_for(
'opensearch')
445 'method': request.preferences.get_value(
'method'),
446 'autocomplete': request.preferences.get_value(
'autocomplete'),
450 kwargs[
'urlparse'] = urlparse
453 kwargs[
'scripts'] = set()
454 for plugin
in request.user_plugins:
455 for script
in plugin.js_dependencies:
456 kwargs[
'scripts'].add(script)
459 kwargs[
'styles'] = set()
460 for plugin
in request.user_plugins:
461 for css
in plugin.css_dependencies:
462 kwargs[
'styles'].add(css)
464 start_time = default_timer()
465 result = render_template(
'{}/{}'.
format(kwargs[
'theme'], template_name), **kwargs)
466 request.render_time += default_timer() - start_time
473 request.start_time = default_timer()
474 request.render_time = 0
478 client_pref = ClientPref.from_http_request(request)
480 preferences =
Preferences(themes, list(categories.keys()), engines, plugins, client_pref)
482 user_agent = request.headers.get(
'User-Agent',
'').lower()
483 if 'webkit' in user_agent
and 'android' in user_agent:
484 preferences.key_value_settings[
'method'].value =
'GET'
485 request.preferences = preferences
488 preferences.parse_dict(request.cookies)
490 except Exception
as e:
491 logger.exception(e, exc_info=
True)
492 request.errors.append(gettext(
'Invalid settings, please edit your preferences'))
496 request.form = dict(request.form.items())
497 for k, v
in request.args.items():
498 if k
not in request.form:
501 if request.form.get(
'preferences'):
502 preferences.parse_encoded_data(request.form[
'preferences'])
505 preferences.parse_dict(request.form)
506 except Exception
as e:
507 logger.exception(e, exc_info=
True)
508 request.errors.append(gettext(
'Invalid settings'))
512 if not preferences.get_value(
"language"):
514 preferences.parse_dict({
"language": language})
515 logger.debug(
'set language %s (from browser)', preferences.get_value(
"language"))
519 if not preferences.get_value(
"locale"):
521 preferences.parse_dict({
"locale": locale})
522 logger.debug(
'set locale %s (from browser)', preferences.get_value(
"locale"))
525 request.user_plugins = []
526 allowed_plugins = preferences.plugins.get_enabled()
527 disabled_plugins = preferences.plugins.get_disabled()
528 for plugin
in plugins:
529 if (plugin.default_on
and plugin.id
not in disabled_plugins)
or plugin.id
in allowed_plugins:
530 request.user_plugins.append(plugin)
545 total_time = default_timer() - request.start_time
547 'total;dur=' + str(round(total_time * 1000, 3)),
548 'render;dur=' + str(round(request.render_time * 1000, 3)),
550 if len(request.timings) > 0:
551 timings = sorted(request.timings, key=
lambda t: t.total)
553 'total_' + str(i) +
'_' + t.engine +
';dur=' + str(round(t.total * 1000, 3))
for i, t
in enumerate(timings)
556 'load_' + str(i) +
'_' + t.engine +
';dur=' + str(round(t.load * 1000, 3))
557 for i, t
in enumerate(timings)
560 timings_all = timings_all + timings_total + timings_load
561 response.headers.add(
'Server-Timing',
', '.join(timings_all))
633 """Search query in q and return results.
635 Supported outputs: html, json, csv, rss.
641 output_format = request.form.get(
'format',
'html')
642 if output_format
not in OUTPUT_FORMATS:
643 output_format =
'html'
645 if output_format
not in settings[
'search'][
'formats']:
649 if not request.form.get(
'q'):
650 if output_format ==
'html':
654 selected_categories=get_selected_categories(request.preferences, request.form),
661 raw_text_query =
None
662 result_container =
None
664 search_query, raw_text_query, _, _, selected_locale = get_search_query_from_webapp(
665 request.preferences, request.form
668 result_container = search.search()
670 except SearxParameterException
as e:
671 logger.exception(
'search error: SearxParameterException')
673 except Exception
as e:
674 logger.exception(e, exc_info=
True)
675 return index_error(output_format, gettext(
'search error')), 500
678 if result_container.redirect_url:
679 return redirect(result_container.redirect_url)
683 request.timings = result_container.get_timings()
687 if output_format ==
'json':
689 response = webutils.get_json_response(search_query, result_container)
690 return Response(response, mimetype=
'application/json')
692 if output_format ==
'csv':
695 webutils.write_csv_response(csv, result_container)
698 response = Response(csv.stream.read(), mimetype=
'application/csv')
699 cont_disp =
'attachment;Filename=searx_-_{0}.csv'.
format(search_query.query)
700 response.headers.add(
'Content-Disposition', cont_disp)
705 current_template =
None
706 previous_result =
None
708 results = result_container.get_ordered_results()
710 if search_query.redirect_to_first_result
and results:
711 return redirect(results[0][
'url'], 302)
713 for result
in results:
714 if output_format ==
'html':
715 if 'content' in result
and result[
'content']:
716 result[
'content'] = highlight_content(escape(result[
'content'][:1024]), search_query.query)
717 if 'title' in result
and result[
'title']:
718 result[
'title'] = highlight_content(escape(result[
'title']
or ''), search_query.query)
721 result[
'pretty_url'] = webutils.prettify_url(result[
'url'])
722 if result.get(
'publishedDate'):
724 result[
'pubdate'] = result[
'publishedDate'].strftime(
'%Y-%m-%d %H:%M:%S%z')
726 result[
'publishedDate'] =
None
728 result[
'publishedDate'] = webutils.searxng_l10n_timespan(result[
'publishedDate'])
732 if current_template != result.get(
'template'):
733 result[
'open_group'] =
True
735 previous_result[
'close_group'] =
True
736 current_template = result.get(
'template')
737 previous_result = result
740 previous_result[
'close_group'] =
True
744 if output_format ==
'rss':
746 'opensearch_response_rss.xml',
749 number_of_results=result_container.number_of_results,
751 return Response(response_rss, mimetype=
'text/xml')
756 suggestion_urls = list(
758 lambda suggestion: {
'url': raw_text_query.changeQuery(suggestion).getFullQuery(),
'title': suggestion},
759 result_container.suggestions,
763 correction_urls = list(
765 lambda correction: {
'url': raw_text_query.changeQuery(correction).getFullQuery(),
'title': correction},
766 result_container.corrections,
771 engine_timings = sorted(result_container.get_timings(), reverse=
True, key=
lambda e: e.total)
772 max_response_time = engine_timings[0].total
if engine_timings
else None
773 engine_timings_pairs = [(timing.engine, timing.total)
for timing
in engine_timings]
783 selected_categories = search_query.categories,
784 pageno = search_query.pageno,
785 time_range = search_query.time_range
or '',
786 number_of_results = format_decimal(result_container.number_of_results),
787 suggestions = suggestion_urls,
788 answers = result_container.answers,
789 corrections = correction_urls,
790 infoboxes = result_container.infoboxes,
791 engine_data = result_container.engine_data,
792 paging = result_container.paging,
793 unresponsive_engines = webutils.get_translated_errors(
794 result_container.unresponsive_engines
796 current_locale = request.preferences.get_value(
"locale"),
797 current_language = selected_locale,
798 search_language = match_locale(
799 search.search_query.lang,
800 settings[
'search'][
'languages'],
801 fallback=request.preferences.get_value(
"language")
803 timeout_limit = request.form.get(
'timeout_limit',
None),
804 timings = engine_timings_pairs,
805 max_response_time = max_response_time
810@app.route('/about', methods=['GET'])
835 """Return autocompleter results"""
841 disabled_engines = request.preferences.engines.get_disabled()
844 raw_text_query =
RawTextQuery(request.form.get(
'q',
''), disabled_engines)
845 sug_prefix = raw_text_query.getQuery()
849 if len(raw_text_query.autocomplete_list) == 0
and len(sug_prefix) > 0:
852 sxng_locale = request.preferences.get_value(
'language')
853 backend_name = request.preferences.get_value(
'autocomplete')
855 for result
in search_autocomplete(backend_name, sug_prefix, sxng_locale):
858 if result != sug_prefix:
859 results.append(raw_text_query.changeQuery(result).getFullQuery())
861 if len(raw_text_query.autocomplete_list) > 0:
862 for autocomplete_text
in raw_text_query.autocomplete_list:
863 results.append(raw_text_query.get_autocomplete_full_query(autocomplete_text))
865 for answers
in ask(raw_text_query):
866 for answer
in answers:
867 results.append(str(answer[
'answer']))
869 if request.headers.get(
'X-Requested-With') ==
'XMLHttpRequest':
871 suggestions = json.dumps(results)
872 mimetype =
'application/json'
875 suggestions = json.dumps([sug_prefix, results])
876 mimetype =
'application/x-suggestions+json'
878 suggestions = escape(suggestions,
False)
879 return Response(suggestions, mimetype=mimetype)
882@app.route('/preferences', methods=['GET', 'POST'])
884 """Render preferences page && save user preferences"""
890 if request.args.get(
'preferences')
or request.form.get(
'preferences'):
891 resp = make_response(redirect(url_for(
'index', _external=
True)))
892 return request.preferences.save(resp)
895 if request.method ==
'POST':
896 resp = make_response(redirect(url_for(
'index', _external=
True)))
898 request.preferences.parse_form(request.form)
899 except ValidationException:
900 request.errors.append(gettext(
'Invalid settings, please edit your preferences'))
902 return request.preferences.save(resp)
905 image_proxy = request.preferences.get_value(
'image_proxy')
906 disabled_engines = request.preferences.engines.get_disabled()
907 allowed_plugins = request.preferences.plugins.get_enabled()
910 filtered_engines = dict(filter(
lambda kv: request.preferences.validate_token(kv[1]), engines.items()))
912 engines_by_category = {}
915 engines_by_category[c] = [e
for e
in categories[c]
if e.name
in filtered_engines]
917 list.sort(engines_by_category[c], key=
lambda e: e.name)
923 for _, e
in filtered_engines.items():
924 h = histogram(
'engine', e.name,
'time',
'total')
925 median = round(h.percentage(50), 1)
if h.count > 0
else None
926 rate80 = round(h.percentage(80), 1)
if h.count > 0
else None
927 rate95 = round(h.percentage(95), 1)
if h.count > 0
else None
929 max_rate95 = max(max_rate95, rate95
or 0)
931 result_count_sum = histogram(
'engine', e.name,
'result',
'count').sum
932 successful_count = counter(
'engine', e.name,
'search',
'count',
'successful')
933 result_count = int(result_count_sum / float(successful_count))
if successful_count
else 0
939 'warn_timeout': e.timeout > settings[
'outgoing'][
'request_timeout'],
940 'supports_selected_language': e.traits.is_locale_supported(
941 str(request.preferences.get_value(
'language')
or 'all')
943 'result_count': result_count,
949 engine_errors = get_engine_errors(filtered_engines)
950 checker_results = checker_get_result()
952 checker_results[
'engines']
if checker_results[
'status'] ==
'ok' and 'engines' in checker_results
else {}
954 for _, e
in filtered_engines.items():
955 checker_result = checker_results.get(e.name, {})
956 checker_success = checker_result.get(
'success',
True)
957 errors = engine_errors.get(e.name)
or []
958 if counter(
'engine', e.name,
'search',
'count',
'sent') == 0:
961 elif checker_success
and not errors:
963 elif 'simple' in checker_result.get(
'errors', {}):
969 reliability = 100 - sum([error[
'percentage']
for error
in errors
if not error.get(
'secondary')])
971 reliabilities[e.name] = {
972 'reliability': reliability,
974 'checker': checker_results.get(e.name, {}).get(
'errors', {}).keys(),
978 reliabilities_errors = []
980 error_user_text =
None
981 if error.get(
'secondary')
or 'exception_classname' not in error:
983 error_user_text = exception_classname_to_text.get(error.get(
'exception_classname'))
985 error_user_text = exception_classname_to_text[
None]
986 if error_user_text
not in reliabilities_errors:
987 reliabilities_errors.append(error_user_text)
988 reliabilities[e.name][
'errors'] = reliabilities_errors
992 for _, e
in filtered_engines.items():
993 supports_selected_language = e.traits.is_locale_supported(
994 str(request.preferences.get_value(
'language')
or 'all')
996 safesearch = e.safesearch
997 time_range_support = e.time_range_support
998 for checker_test_name
in checker_results.get(e.name, {}).get(
'errors', {}):
999 if supports_selected_language
and checker_test_name.startswith(
'lang_'):
1000 supports_selected_language =
'?'
1001 elif safesearch
and checker_test_name ==
'safesearch':
1003 elif time_range_support
and checker_test_name ==
'time_range':
1004 time_range_support =
'?'
1005 supports[e.name] = {
1006 'supports_selected_language': supports_selected_language,
1007 'safesearch': safesearch,
1008 'time_range_support': time_range_support,
1014 selected_categories = get_selected_categories(request.preferences, request.form),
1015 locales = LOCALE_NAMES,
1016 current_locale = request.preferences.get_value(
"locale"),
1017 image_proxy = image_proxy,
1018 engines_by_category = engines_by_category,
1020 max_rate95 = max_rate95,
1021 reliabilities = reliabilities,
1022 supports = supports,
1024 {
'info': a.self_info(),
'keywords': a.keywords}
1027 disabled_engines = disabled_engines,
1028 autocomplete_backends = autocomplete_backends,
1029 favicon_resolver_names = favicons.proxy.CFG.resolver_map.keys(),
1030 shortcuts = {y: x
for x, y
in engine_shortcuts.items()},
1033 doi_resolvers = settings[
'doi_resolvers'],
1034 current_doi_resolver = get_doi_resolver(request.preferences),
1035 allowed_plugins = allowed_plugins,
1036 preferences_url_params = request.preferences.get_as_url_params(),
1037 locked_preferences = settings[
'preferences'][
'lock'],
1050 url = request.args.get(
'url')
1054 if not is_hmac_of(settings[
'server'][
'secret_key'], url.encode(), request.args.get(
'h',
'')):
1057 maximum_size = 5 * 1024 * 1024
1058 forward_resp =
False
1062 'User-Agent': gen_useragent(),
1063 'Accept':
'image/webp,*/*',
1064 'Accept-Encoding':
'gzip, deflate',
1068 set_context_network_name(
'image_proxy')
1069 resp, stream = http_stream(method=
'GET', url=url, headers=request_headers, allow_redirects=
True)
1070 content_length = resp.headers.get(
'Content-Length')
1071 if content_length
and content_length.isdigit()
and int(content_length) > maximum_size:
1072 return 'Max size', 400
1074 if resp.status_code != 200:
1075 logger.debug(
'image-proxy: wrong response code: %i', resp.status_code)
1076 if resp.status_code >= 400:
1077 return '', resp.status_code
1080 if not resp.headers.get(
'Content-Type',
'').startswith(
'image/')
and not resp.headers.get(
1082 ).startswith(
'binary/octet-stream'):
1083 logger.debug(
'image-proxy: wrong content-type: %s', resp.headers.get(
'Content-Type',
''))
1087 except httpx.HTTPError:
1088 logger.exception(
'HTTP error')
1091 if resp
and not forward_resp:
1096 except httpx.HTTPError:
1097 logger.exception(
'HTTP error on closing')
1100 nonlocal resp, stream
1106 except httpx.HTTPError
as e:
1107 logger.debug(
'Exception while closing response', e)
1110 headers = dict_subset(resp.headers, {
'Content-Type',
'Content-Encoding',
'Content-Length',
'Length'})
1111 response = Response(stream, mimetype=resp.headers[
'Content-Type'], headers=headers, direct_passthrough=
True)
1112 response.call_on_close(close_stream)
1114 except httpx.HTTPError:
1119@app.route('/engine_descriptions.json', methods=['GET'])
1121 locale = get_locale().split(
'_')[0]
1122 result = ENGINE_DESCRIPTIONS[
'en'].copy()
1124 for engine, description
in ENGINE_DESCRIPTIONS.get(locale, {}).items():
1125 result[engine] = description
1126 for engine, description
in result.items():
1127 if len(description) == 2
and description[1] ==
'ref':
1128 ref_engine, ref_lang = description[0].split(
':')
1129 description = ENGINE_DESCRIPTIONS[ref_lang][ref_engine]
1130 if isinstance(description, str):
1131 description = [description,
'wikipedia']
1132 result[engine] = description
1135 for engine_name, engine_mod
in engines.items():
1136 descr = getattr(engine_mod,
'about', {}).get(
'description',
None)
1137 if descr
is not None:
1138 result[engine_name] = [descr,
"SearXNG config"]
1140 return jsonify(result)
1143@app.route('/stats', methods=['GET'])
1145 """Render engine statistics page."""
1146 sort_order = request.args.get(
'sort', default=
'name', type=str)
1147 selected_engine_name = request.args.get(
'engine', default=
None, type=str)
1149 filtered_engines = dict(filter(
lambda kv: request.preferences.validate_token(kv[1]), engines.items()))
1150 if selected_engine_name:
1151 if selected_engine_name
not in filtered_engines:
1152 selected_engine_name =
None
1154 filtered_engines = [selected_engine_name]
1156 checker_results = checker_get_result()
1158 checker_results[
'engines']
if checker_results[
'status'] ==
'ok' and 'engines' in checker_results
else {}
1161 engine_stats = get_engines_stats(filtered_engines)
1162 engine_reliabilities = get_reliabilities(filtered_engines, checker_results)
1164 if sort_order
not in STATS_SORT_PARAMETERS:
1167 reverse, key_name, default_value = STATS_SORT_PARAMETERS[sort_order]
1169 def get_key(engine_stat):
1170 reliability = engine_reliabilities.get(engine_stat[
'name'], {}).get(
'reliability', 0)
1171 reliability_order = 0
if reliability
else 1
1172 if key_name ==
'reliability':
1174 reliability_order = 0
1176 key = engine_stat.get(key_name)
or default_value
1178 reliability_order = 1 - reliability_order
1179 return (reliability_order, key, engine_stat[
'name'])
1181 technical_report = []
1182 for error
in engine_reliabilities.get(selected_engine_name, {}).get(
'errors', []):
1183 technical_report.append(
1185 Error: {error['exception_classname'] or error['log_message']} \
1186 Parameters: {error['log_parameters']} \
1187 File name: {error['filename'] }:{ error['line_no'] } \
1188 Error Function: {error['function']} \
1189 Code: {error['code']} \
1194 technical_report =
' '.join(technical_report)
1196 engine_stats[
'time'] = sorted(engine_stats[
'time'], reverse=reverse, key=get_key)
1200 sort_order = sort_order,
1201 engine_stats = engine_stats,
1202 engine_reliabilities = engine_reliabilities,
1203 selected_engine_name = selected_engine_name,
1204 searx_git_branch = GIT_BRANCH,
1205 technical_report = technical_report,
1210@app.route('/stats/errors', methods=['GET'])