.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
mediawiki.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""The MediaWiki engine is a *generic* engine to **query** Wikimedia wikis by
3the `MediaWiki Action API`_. For a `query action`_ all Wikimedia wikis have
4endpoints that follow this pattern::
5
6 https://{base_url}/w/api.php?action=query&list=search&format=json
7
8.. note::
9
10 In its actual state, this engine is implemented to parse JSON result
11 (`format=json`_) from a search query (`list=search`_). If you need other
12 ``action`` and ``list`` types ask SearXNG developers to extend the
13 implementation according to your needs.
14
15.. _MediaWiki Action API: https://www.mediawiki.org/wiki/API:Main_page
16.. _query action: https://www.mediawiki.org/w/api.php?action=help&modules=query
17.. _`list=search`: https://www.mediawiki.org/w/api.php?action=help&modules=query%2Bsearch
18.. _`format=json`: https://www.mediawiki.org/w/api.php?action=help&modules=json
19
20Configuration
21=============
22
23Request:
24
25- :py:obj:`base_url`
26- :py:obj:`search_type`
27- :py:obj:`srenablerewrites`
28- :py:obj:`srsort`
29- :py:obj:`srprop`
30
31Implementations
32===============
33
34"""
35
36from datetime import datetime
37from urllib.parse import urlencode, quote
38
39from searx.utils import html_to_text
40
41# about
42about = {
43 "website": None,
44 "wikidata_id": None,
45 "official_api_documentation": 'https://www.mediawiki.org/w/api.php?action=help&modules=query',
46 "use_official_api": True,
47 "require_api_key": False,
48 "results": 'JSON',
49}
50
51# engine dependent config
52categories = ['general']
53paging = True
54number_of_results = 5
55
56search_type: str = 'nearmatch'
57"""Which type of search to perform. One of the following values: ``nearmatch``,
58``text`` or ``title``.
59
60See ``srwhat`` argument in `list=search`_ documentation.
61"""
62
63srenablerewrites: bool = True
64"""Enable internal query rewriting (Type: boolean). Some search backends can
65rewrite the query into another which is thought to provide better results, for
66instance by correcting spelling errors.
67
68See ``srenablerewrites`` argument in `list=search`_ documentation.
69"""
70
71srsort: str = 'relevance'
72"""Set the sort order of returned results. One of the following values:
73``create_timestamp_asc``, ``create_timestamp_desc``, ``incoming_links_asc``,
74``incoming_links_desc``, ``just_match``, ``last_edit_asc``, ``last_edit_desc``,
75``none``, ``random``, ``relevance``, ``user_random``.
76
77See ``srenablerewrites`` argument in `list=search`_ documentation.
78"""
79
80srprop: str = 'sectiontitle|snippet|timestamp|categorysnippet'
81"""Which properties to return.
82
83See ``srprop`` argument in `list=search`_ documentation.
84"""
85
86base_url: str = 'https://{language}.wikipedia.org/'
87"""Base URL of the Wikimedia wiki.
88
89``{language}``:
90 ISO 639-1 language code (en, de, fr ..) of the search language.
91"""
92
93api_path: str = 'w/api.php'
94"""The path the PHP api is listening on.
95
96The default path should work fine usually.
97"""
98
99timestamp_format = '%Y-%m-%dT%H:%M:%SZ'
100"""The longhand version of MediaWiki time strings."""
101
102
103def request(query, params):
104
105 # write search-language back to params, required in response
106
107 if params['language'] == 'all':
108 params['language'] = 'en'
109 else:
110 params['language'] = params['language'].split('-')[0]
111
112 api_url = f"{base_url.rstrip('/')}/{api_path}?".format(language=params['language'])
113 offset = (params['pageno'] - 1) * number_of_results
114
115 args = {
116 'action': 'query',
117 'list': 'search',
118 'format': 'json',
119 'srsearch': query,
120 'sroffset': offset,
121 'srlimit': number_of_results,
122 'srwhat': search_type,
123 'srprop': srprop,
124 'srsort': srsort,
125 }
126 if srenablerewrites:
127 args['srenablerewrites'] = '1'
128
129 params['url'] = api_url + urlencode(args)
130 return params
131
132
133# get response from search-request
134def response(resp):
135
136 results = []
137 search_results = resp.json()
138
139 # return empty array if there are no results
140 if not search_results.get('query', {}).get('search'):
141 return []
142
143 for result in search_results['query']['search']:
144
145 if result.get('snippet', '').startswith('#REDIRECT'):
146 continue
147
148 title = result['title']
149 sectiontitle = result.get('sectiontitle')
150 content = html_to_text(result.get('snippet', ''))
151 metadata = html_to_text(result.get('categorysnippet', ''))
152 timestamp = result.get('timestamp')
153
154 url = (
155 base_url.format(language=resp.search_params['language']) + 'wiki/' + quote(title.replace(' ', '_').encode())
156 )
157 if sectiontitle:
158 # in case of sectiontitle create a link to the section in the wiki page
159 url += '#' + quote(sectiontitle.replace(' ', '_').encode())
160 title += ' / ' + sectiontitle
161
162 item = {'url': url, 'title': title, 'content': content, 'metadata': metadata}
163
164 if timestamp:
165 item['publishedDate'] = datetime.strptime(timestamp, timestamp_format)
166
167 results.append(item)
168
169 # return results
170 return results
request(query, params)
Definition mediawiki.py:103