Files
searxng/searx/engines/currency_convert.py
T

59 lines
1.7 KiB
Python
Raw Normal View History

2021-01-13 11:31:25 +01:00
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Currency convert (DuckDuckGo)"""
2021-01-13 11:31:25 +01:00
import typing as t
2016-11-30 18:43:03 +01:00
import json
from searx.result_types import EngineResults
2020-10-05 13:50:33 +02:00
if t.TYPE_CHECKING:
from searx.search.processors import OnlineCurrenciesParams
from searx.extended_types import SXNG_Response
2021-01-13 11:31:25 +01:00
# about
about = {
"website": "https://duckduckgo.com/",
"wikidata_id": "Q12805",
"official_api_documentation": "https://duckduckgo.com/api",
2021-01-13 11:31:25 +01:00
"use_official_api": False,
"require_api_key": False,
"results": "JSONP",
"description": "Service from DuckDuckGo.",
2021-01-13 11:31:25 +01:00
}
2013-11-04 21:47:16 +01:00
engine_type = "online_currency"
categories = ["currency", "general"]
base_url = "https://duckduckgo.com/js/spice/currency/1/%(from_iso4217)s/%(to_iso4217)s"
ddg_link_url = "https://duckduckgo.com/?q=%(from_iso4217)s+to+%(to_iso4217)s"
2013-11-04 21:47:16 +01:00
weight = 100
def request(query: str, params: "OnlineCurrenciesParams") -> None: # pylint: disable=unused-argument
params["url"] = base_url % params
2013-11-04 21:47:16 +01:00
def response(resp: "SXNG_Response") -> EngineResults:
res = EngineResults()
2023-09-27 15:50:49 -07:00
# remove first and last lines to get only json
json_resp = resp.text[resp.text.find("\n") + 1 : resp.text.rfind("\n") - 2]
2013-11-04 21:47:16 +01:00
try:
2023-09-27 15:50:49 -07:00
conversion_rate = float(json.loads(json_resp)["to"][0]["mid"])
except IndexError:
return res
params: OnlineCurrenciesParams = resp.search_params # pyright: ignore[reportAssignmentType]
answer = "{0} {1} = {2} {3} (1 {5} : {4} {6})".format(
params["amount"],
params["from_iso4217"],
params["amount"] * conversion_rate,
params["to_iso4217"],
conversion_rate,
params["from_name"],
params["to_name"],
)
url = ddg_link_url % params
res.add(res.types.Answer(answer=answer, url=url))
return res