.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
reddit.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""Reddit
3
4"""
5
6import json
7from datetime import datetime
8from urllib.parse import urlencode, urljoin, urlparse
9
10# about
11about = {
12 "website": 'https://www.reddit.com/',
13 "wikidata_id": 'Q1136',
14 "official_api_documentation": 'https://www.reddit.com/dev/api',
15 "use_official_api": True,
16 "require_api_key": False,
17 "results": 'JSON',
18}
19
20# engine dependent config
21categories = ['social media']
22page_size = 25
23
24# search-url
25base_url = 'https://www.reddit.com/'
26search_url = base_url + 'search.json?{query}'
27
28
29def request(query, params):
30
31 query = urlencode({'q': query, 'limit': page_size})
32 params['url'] = search_url.format(query=query)
33
34 return params
35
36
37def response(resp):
38
39 img_results = []
40 text_results = []
41
42 search_results = json.loads(resp.text)
43
44 # return empty array if there are no results
45 if 'data' not in search_results:
46 return []
47
48 posts = search_results.get('data', {}).get('children', [])
49
50 # process results
51 for post in posts:
52 data = post['data']
53
54 # extract post information
55 params = {'url': urljoin(base_url, data['permalink']), 'title': data['title']}
56
57 # if thumbnail field contains a valid URL, we need to change template
58 thumbnail = data['thumbnail']
59 url_info = urlparse(thumbnail)
60 # netloc & path
61 if url_info[1] != '' and url_info[2] != '':
62 params['img_src'] = data['url']
63 params['thumbnail_src'] = thumbnail
64 params['template'] = 'images.html'
65 img_results.append(params)
66 else:
67 created = datetime.fromtimestamp(data['created_utc'])
68 content = data['selftext']
69 if len(content) > 500:
70 content = content[:500] + '...'
71 params['content'] = content
72 params['publishedDate'] = created
73 text_results.append(params)
74
75 # show images first and text results second
76 return img_results + text_results
request(query, params)
Definition reddit.py:29