.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
currency_convert.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""Currency convert (DuckDuckGo)
3"""
4
5import json
6from searx.result_types import EngineResults
7
8# about
9about = {
10 "website": 'https://duckduckgo.com/',
11 "wikidata_id": 'Q12805',
12 "official_api_documentation": 'https://duckduckgo.com/api',
13 "use_official_api": False,
14 "require_api_key": False,
15 "results": 'JSONP',
16 "description": "Service from DuckDuckGo.",
17}
18
19engine_type = 'online_currency'
20categories = []
21base_url = 'https://duckduckgo.com/js/spice/currency/1/{0}/{1}'
22weight = 100
23
24https_support = True
25
26
27def request(_query, params):
28 params['url'] = base_url.format(params['from'], params['to'])
29 return params
30
31
32def response(resp) -> EngineResults:
33 res = EngineResults()
34
35 # remove first and last lines to get only json
36 json_resp = resp.text[resp.text.find('\n') + 1 : resp.text.rfind('\n') - 2]
37 try:
38 conversion_rate = float(json.loads(json_resp)["to"][0]["mid"])
39 except IndexError:
40 return res
41 answer = '{0} {1} = {2} {3}, 1 {1} ({5}) = {4} {3} ({6})'.format(
42 resp.search_params['amount'],
43 resp.search_params['from'],
44 resp.search_params['amount'] * conversion_rate,
45 resp.search_params['to'],
46 conversion_rate,
47 resp.search_params['from_name'],
48 resp.search_params['to_name'],
49 )
50
51 url = f"https://duckduckgo.com/?q={resp.search_params['from']}+to+{resp.search_params['to']}"
52 res.add(res.types.Answer(answer=answer, url=url))
53 return res