1
0
Fork 0
mirror of https://github.com/Findus23/HNReader.git synced 2024-09-19 15:23:44 +02:00
HNReader/hnapi/__init__.py

60 lines
1.9 KiB
Python
Raw Normal View History

2021-04-09 16:17:53 +02:00
import asyncio
2021-04-08 22:29:27 +02:00
import json
2021-04-09 16:17:53 +02:00
from aiohttp import ClientSession
2021-04-08 22:29:27 +02:00
from redis import Redis
API_BASEURL = "https://hacker-news.firebaseio.com/v0/"
class HNClient:
2021-04-09 16:17:53 +02:00
def __init__(self, session: ClientSession, redis: Redis):
self.s = session
2021-04-08 22:29:27 +02:00
self.r = redis
2021-04-09 16:17:53 +02:00
async def get_item(self, item_id: int, remove_kids=True):
2021-04-08 22:29:27 +02:00
key = f"hnclient_item_{item_id}"
cache = self.r.get(key)
if cache:
return json.loads(cache)
url = f"{API_BASEURL}item/{item_id}.json"
2021-04-09 16:17:53 +02:00
async with self.s.get(url) as response:
response.raise_for_status()
text = await response.text()
item = json.loads(text)
self.r.set(key, text, ex=60 * 15)
2021-04-08 22:29:27 +02:00
if "kids" in item and remove_kids:
del item["kids"]
return item
2021-04-09 16:17:53 +02:00
async def get_full_item(self, item_id: int):
item = await self.get_item(item_id, remove_kids=False)
2021-04-08 22:29:27 +02:00
if "kids" in item:
2021-04-09 16:17:53 +02:00
tasks = []
for kid in item["kids"]:
task = asyncio.ensure_future(self.get_full_item(kid))
tasks.append(task)
kids = await asyncio.gather(*tasks)
2021-04-08 22:29:27 +02:00
item["kids"] = kids
return item
2021-04-09 16:17:53 +02:00
async def get_stories(self, page: str, limit=25, offset=0):
2021-04-08 22:29:27 +02:00
key = f"hnclient_stories_{page}_{limit}"
cached = self.r.get(key)
if cached:
return json.loads(cached)
url = f"{API_BASEURL}{page}.json"
2021-04-09 16:17:53 +02:00
async with self.s.get(url) as response:
response.raise_for_status()
stories = await response.json()
stories = stories[offset:limit]
tasks = []
for id in stories:
task = asyncio.ensure_future(self.get_item(id))
tasks.append(task)
full_stories = await asyncio.gather(*tasks)
2021-04-08 22:29:27 +02:00
self.r.set(key, json.dumps(full_stories), ex=60 * 15)
return full_stories