1
0
mirror of https://github.com/searxng/searxng.git synced 2024-11-16 17:40:11 +01:00
searxng/searx/engines/reddit.py

77 lines
2.0 KiB
Python
Raw Normal View History

2016-03-25 14:30:32 +01:00
"""
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 datetime import datetime
2016-11-30 18:43:03 +01:00
from searx.url_utils import urlencode, urljoin, urlparse
2016-03-25 14:30:32 +01:00
# engine dependent config
categories = ['general', 'images', 'news', 'social media']
page_size = 25
# search-url
base_url = 'https://www.reddit.com/'
search_url = base_url + 'search.json?{query}'
2016-03-25 14:30:32 +01:00
# do search-request
def request(query, params):
2016-11-30 18:43:03 +01:00
query = urlencode({'q': query, 'limit': page_size})
2016-03-25 14:30:32 +01:00
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': urljoin(base_url, data['permalink']),
2016-03-25 14:30:32 +01:00
'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['img_src'] = data['url']
2016-03-25 14:30:32 +01:00
params['thumbnail_src'] = thumbnail
params['template'] = 'images.html'
img_results.append(params)
else:
created = datetime.fromtimestamp(data['created_utc'])
content = data['selftext']
if len(content) > 500:
content = content[:500] + '...'
params['content'] = content
2016-03-25 14:30:32 +01:00
params['publishedDate'] = created
text_results.append(params)
# show images first and text results second
return img_results + text_results