Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create ocflib Tools for Announcements #257

Draft
wants to merge 13 commits into
base: master
Choose a base branch
from
71 changes: 71 additions & 0 deletions ocflib/lab/announcements.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""Announcements handling"""
from collections import namedtuple
from requests import get

from yaml import safe_load
from typing import NamedTuple

ANNOUNCEMENTS_REPO = (
"https://api.github.com/repos/ocf/announcements/contents/announcements/{id}"
)

# TODO: cache
# TODO: request session for better efficiency

Metadata = namedtuple("Metadata", ["title", "date", "author", "tags", "summary"])


def get_all_announcements():
"""Get announcements from the announcements repo"""
posts = get(
url=ANNOUNCEMENTS_REPO.format(id=""),
headers={"Accept": "application/vnd.github+json"},
)
posts.raise_for_status()

return posts.json()


def get_announcement(id: str) -> str:
"""Get one particular announcement from the announcements repo"""
posts = get(
url=ANNOUNCEMENTS_REPO.format(id=id + ".md"),
headers={"Accept": "application/vnd.github.raw"},
)
posts.raise_for_status()

return posts.text


def get_id(post: str) -> str:
"""Get announcement id"""
return post["name"][:-3]
vicshi06 marked this conversation as resolved.
Show resolved Hide resolved


def get_metadata(post: str) -> Metadata:
"""Get the metadata from one announcement"""
meta_dict = safe_load(post.split("---")[1])

metadata = Metadata(
title=meta_dict["title"],
date=meta_dict["date"],
author=meta_dict["author"],
tags=meta_dict["tags"],
summary=meta_dict["summary"],
)
return metadata


def get_announcements(num: int) -> list[str]:
"""Get the last num announcements"""
posts = get_all_announcements()

# get the last num posts in reverse order
return [get_announcement(get_id(post)) for post in posts[-1 : -num - 1 : -1]]


# print(get_all_announcements())
vicshi06 marked this conversation as resolved.
Show resolved Hide resolved
# print(get_announcement("2002-01-01-00"))
# print(get_metadata(get_announcement("2002-01-01-00")))
# print(get_all_ids())
# print(get_announcements(2))