import os import json import aiofiles DATE_FORMAT = "%Y-%m-%d" def get_datadir(): return os.getenv('SB_DATADIR') def get_article_path(slug): return os.path.join(get_datadir(), 'articles', slug + '.json') def load_article_by_slug(slug): with open(get_article_path(slug), 'r') as f: return json.load(f) def save_article(data): with open(get_article_path(data['slug']), 'r') as f: return json.save(data, f) def get_date_report_path(date): dstr = date.strftime(DATE_FORMAT) return os.path.join(get_datadir(), 'days', dstr + '.json') def load_date_report(date): path = get_date_report_path(date) if not os.path.exists(path): return [] with open(path, 'r') as f: return json.load(f) async def load_date_report_async(date): path = get_date_report_path(date) if not os.path.exists(path): return [] async with aiofiles.open(path, 'r') as f: return json.loads(await f.read()) def save_date_report(date, data): path = get_date_report_path(date) os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) with open(path, 'w') as f: json.dump(data, f) async def save_date_report_async(date, data): path = get_date_report_path(date) os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) async with aiofiles.open(path, 'w') as f: await f.write(json.dumps(data))