Add search suggestions cache

This commit is contained in:
Cadence Ember 2020-08-12 00:40:25 +12:00
parent 9ee1f3ce89
commit 9943847e9d
No known key found for this signature in database
GPG Key ID: 128B99B1B74A6412
1 changed files with 7 additions and 1 deletions

View File

@ -104,6 +104,7 @@ class Second(object):
def __init__(self): def __init__(self):
self.video_cache = TTLCache(maxsize=50, ttl=300) self.video_cache = TTLCache(maxsize=50, ttl=300)
self.search_cache = TTLCache(maxsize=50, ttl=300) self.search_cache = TTLCache(maxsize=50, ttl=300)
self.search_suggestions_cache = TTLCache(maxsize=200, ttl=60)
def _cp_dispatch(self, vpath): def _cp_dispatch(self, vpath):
if vpath[:4] == ["api", "manifest", "dash", "id"]: if vpath[:4] == ["api", "manifest", "dash", "id"]:
@ -499,6 +500,9 @@ class Second(object):
@cherrypy.expose @cherrypy.expose
@cherrypy.tools.json_out() @cherrypy.tools.json_out()
def suggestions(self, *, q, **kwargs): def suggestions(self, *, q, **kwargs):
if q in self.search_suggestions_cache:
return self.search_suggestions_cache[q]
params = { params = {
"client": "youtube", "client": "youtube",
"hl": "en", "hl": "en",
@ -515,10 +519,12 @@ class Second(object):
with requests.get("https://clients1.google.com/complete/search", params=params) as r: with requests.get("https://clients1.google.com/complete/search", params=params) as r:
r.raise_for_status() r.raise_for_status()
response = r.json() response = r.json()
return { result = {
"query": q, "query": q,
"suggestions": [s[0] for s in response[1]] "suggestions": [s[0] for s in response[1]]
} }
self.search_suggestions_cache[q] = result
return result
@cherrypy.expose @cherrypy.expose
def vi(self, id, file): def vi(self, id, file):