summaryrefslogtreecommitdiff
path: root/searx/engines/reddit.py
diff options
context:
space:
mode:
authorAdam Tauber <asciimoo@gmail.com>2016-04-14 10:59:31 +0200
committerAdam Tauber <asciimoo@gmail.com>2016-04-14 10:59:31 +0200
commit85c0351dca086c5f652c34048fef290b09e088d9 (patch)
treec45b0cee0f2a4e13704ed376701cbdcbe1e00b27 /searx/engines/reddit.py
parent5544fdb75610bb66d05392289e0f0ad48c13ccf6 (diff)
parent90c51cb4494c90353cc97794eece486bd8bf92dd (diff)
Merge pull request #526 from ukwt/anime
Add a few search engines
Diffstat (limited to 'searx/engines/reddit.py')
-rw-r--r--searx/engines/reddit.py77
1 files changed, 77 insertions, 0 deletions
diff --git a/searx/engines/reddit.py b/searx/engines/reddit.py
new file mode 100644
index 000000000..9729898e5
--- /dev/null
+++ b/searx/engines/reddit.py
@@ -0,0 +1,77 @@
+"""
+ Reddit
+
+ @website https://www.reddit.com/
+ @provide-api yes (https://www.reddit.com/dev/api)
+
+ @using-api yes
+ @results JSON
+ @stable yes
+ @parse url, title, content, thumbnail, publishedDate
+"""
+
+import json
+from cgi import escape
+from urllib import urlencode
+from urlparse import urlparse
+from datetime import datetime
+
+# engine dependent config
+categories = ['general', 'images', 'news', 'social media']
+page_size = 25
+
+# search-url
+search_url = 'https://www.reddit.com/search.json?{query}'
+
+
+# do search-request
+def request(query, params):
+ query = urlencode({'q': query,
+ 'limit': page_size})
+ params['url'] = search_url.format(query=query)
+
+ return params
+
+
+# get response from search-request
+def response(resp):
+ img_results = []
+ text_results = []
+
+ search_results = json.loads(resp.text)
+
+ # return empty array if there are no results
+ if 'data' not in search_results:
+ return []
+
+ posts = search_results.get('data', {}).get('children', [])
+
+ # process results
+ for post in posts:
+ data = post['data']
+
+ # extract post information
+ params = {
+ 'url': data['url'],
+ 'title': data['title']
+ }
+
+ # if thumbnail field contains a valid URL, we need to change template
+ thumbnail = data['thumbnail']
+ url_info = urlparse(thumbnail)
+ # netloc & path
+ if url_info[1] != '' and url_info[2] != '':
+ params['thumbnail_src'] = thumbnail
+ params['template'] = 'images.html'
+ img_results.append(params)
+ else:
+ created = datetime.fromtimestamp(data['created_utc'])
+ content = escape(data['selftext'])
+ if len(content) > 500:
+ content = content[:500] + '...'
+ params['content'] = content
+ params['publishedDate'] = created
+ text_results.append(params)
+
+ # show images first and text results second
+ return img_results + text_results