From 925e8b94295a54c685fe4a22030fdaa86ebd54fa Mon Sep 17 00:00:00 2001 From: Martijn de Vos Date: Fri, 24 Jun 2016 14:43:47 +0200 Subject: [PATCH] Implemented endpoint to get autocompletion terms when searching --- .../Core/Modules/restapi/search_endpoint.py | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/Tribler/Core/Modules/restapi/search_endpoint.py b/Tribler/Core/Modules/restapi/search_endpoint.py index ca36ea7103c..851c074d162 100644 --- a/Tribler/Core/Modules/restapi/search_endpoint.py +++ b/Tribler/Core/Modules/restapi/search_endpoint.py @@ -22,6 +22,8 @@ def __init__(self, session): self.torrent_db_handler = self.session.open_dbhandler(NTFY_TORRENTS) self._logger = logging.getLogger(self.__class__.__name__) + self.putChild("completions", SearchCompletionsEndpoint(session)) + def render_GET(self, request): """ .. http:get:: /search?q=(string:query) @@ -83,3 +85,44 @@ def render_GET(self, request): self._logger.error(exc) return json.dumps({"queried": True}) + + +class SearchCompletionsEndpoint(resource.Resource): + """ + This class is responsible for managing requests regarding the search completions terms of a query. + """ + + def __init__(self, session): + resource.Resource.__init__(self) + self.session = session + self.torrent_db_handler = self.session.open_dbhandler(NTFY_TORRENTS) + + def render_GET(self, request): + """ + .. http:get:: /search/completions?q=(string:query) + + A GET request to this endpoint will return autocompletion suggestions for the given query. For instance, + when searching for "pioneer", this endpoint might return "pioneer one" if that torrent is present in the + local database. This endpoint can be used to suggest terms to users while they type their search query. + + **Example request**: + + .. sourcecode:: none + + curl -X GET http://localhost:8085/search/completions?q=pioneer + + **Example response**: + + .. sourcecode:: javascript + + { + "completions": ["pioneer one", "pioneer movie"] + } + """ + if 'q' not in request.args: + request.setResponseCode(http.BAD_REQUEST) + return json.dumps({"error": "query parameter missing"}) + + keywords = unicode(request.args['q'][0]).lower() + results = self.torrent_db_handler.getAutoCompleteTerms(keywords, max_terms=5) + return json.dumps({"completions": results})