2022-10-04 00:32:29 +00:00
|
|
|
import asyncio
|
2022-11-17 19:53:58 +00:00
|
|
|
import json
|
2023-11-23 23:00:28 +00:00
|
|
|
import httpx
|
2023-10-23 14:47:11 +00:00
|
|
|
from services.rediscache import redis
|
2023-10-05 20:31:21 +00:00
|
|
|
from orm.shout import Shout
|
2022-10-04 00:32:29 +00:00
|
|
|
|
|
|
|
|
|
|
|
class SearchService:
|
|
|
|
lock = asyncio.Lock()
|
|
|
|
cache = {}
|
|
|
|
|
|
|
|
@staticmethod
|
2022-10-04 09:25:59 +00:00
|
|
|
async def init(session):
|
|
|
|
async with SearchService.lock:
|
2023-11-24 01:53:30 +00:00
|
|
|
print("[services.search] did nothing")
|
2022-10-04 09:25:59 +00:00
|
|
|
SearchService.cache = {}
|
2022-10-04 00:32:29 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2022-11-17 19:47:40 +00:00
|
|
|
async def search(text, limit, offset) -> [Shout]:
|
2022-11-17 20:29:04 +00:00
|
|
|
cached = await redis.execute("GET", text)
|
2022-11-17 19:53:58 +00:00
|
|
|
if not cached:
|
|
|
|
async with SearchService.lock:
|
2023-11-23 23:00:28 +00:00
|
|
|
# Use httpx to send a request to ElasticSearch
|
|
|
|
async with httpx.AsyncClient() as client:
|
|
|
|
search_url = f"https://search.discours.io/search?q={text}"
|
|
|
|
response = await client.get(search_url)
|
|
|
|
if response.status_code == 200:
|
|
|
|
payload = response.json()
|
|
|
|
await redis.execute("SET", text, payload)
|
|
|
|
return json.loads(payload)
|
2022-11-17 19:53:58 +00:00
|
|
|
else:
|
|
|
|
return json.loads(cached)
|