Files
qotnews/apiserver/search.py
T
2026-11-12 20:03:38 +00:00

61 lines
2.0 KiB
Python

import logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.DEBUG)
import requests
import settings
SEARCH_ENABLED = bool(settings.MEILI_URL)
def meili_api(method, route, json=None, params=None, parse_json=True):
try:
headers = {'Authorization': 'Bearer ' + settings.MEILI_API_KEY}
r = method(settings.MEILI_URL + route, json=json, params=params, headers=headers, timeout=4)
if r.status_code > 299:
raise Exception('Bad response code ' + str(r.status_code))
if parse_json:
return r.json()
else:
r.encoding = 'utf-8'
return r.text
except KeyboardInterrupt:
raise
except BaseException as e:
logging.error('Problem with MeiliSearch api route: %s: %s', route, str(e))
return False
def create_index(index_uid='qotnews'):
json = dict(uid=index_uid, primaryKey='id')
return meili_api(requests.post, 'indexes', json=json)
def update_settings(index_uid='qotnews'):
json = {
'rankingRules': ['typo', 'words', 'proximity', 'date:desc', 'exactness'],
'searchableAttributes': ['title', 'url', 'author'],
'displayedAttributes': ['id', 'ref', 'source', 'author', 'author_link', 'score', 'date', 'title', 'link', 'url', 'num_comments'],
}
return meili_api(requests.patch, 'indexes/{}/settings'.format(index_uid), json=json)
def init():
if not SEARCH_ENABLED:
logging.info('Search is not enabled, skipping init.')
return
print(create_index())
update_settings()
def put_story(story, index_uid='qotnews'):
if not SEARCH_ENABLED: return
return meili_api(requests.post, 'indexes/{}/documents'.format(index_uid), [story])
def search(q, index_uid='qotnews'):
if not SEARCH_ENABLED: return []
json = dict(q=q, limit=settings.FEED_LENGTH)
r = meili_api(requests.post, 'indexes/{}/search'.format(index_uid), json=json, parse_json=False)
return r
if __name__ == '__main__':
init()
print(search('facebook'))