librus_apix.homework

This module provides functions for retrieving homework assignments from the Librus site, parsing them, and fetching detailed information about specific assignments.

Classes: - Homework: Represents a homework assignment with detailed information such as lesson, teacher, subject, etc.

Functions: - homework_detail: Retrieves detailed information about a specific homework assignment. - get_homework: Retrieves homework assignments within a specified date range.

Usage:

from librus_apix.client import new_client

# Create a new client instance
client = new_client()
client.get_token(username, password)

# Retrieve homework assignments within a specified date range
date_from = "YYYY-MM-DD"
date_to = "YYYY-MM-DD"
homework_assignments = get_homework(client, date_from, date_to)

# Retrieve detailed information about a specific homework assignment
for homework in homework_assignments:
    homework_details = homework_detail(client, homework.href)
  1"""
  2This module provides functions for retrieving homework assignments from the Librus site, parsing them, and fetching detailed information about specific assignments.
  3
  4Classes:
  5    - Homework: Represents a homework assignment with detailed information such as lesson, teacher, subject, etc.
  6
  7Functions:
  8    - homework_detail: Retrieves detailed information about a specific homework assignment.
  9    - get_homework: Retrieves homework assignments within a specified date range.
 10
 11Usage:
 12```python
 13from librus_apix.client import new_client
 14
 15# Create a new client instance
 16client = new_client()
 17client.get_token(username, password)
 18
 19# Retrieve homework assignments within a specified date range
 20date_from = "YYYY-MM-DD"
 21date_to = "YYYY-MM-DD"
 22homework_assignments = get_homework(client, date_from, date_to)
 23
 24# Retrieve detailed information about a specific homework assignment
 25for homework in homework_assignments:
 26    homework_details = homework_detail(client, homework.href)
 27```
 28"""
 29
 30from typing import List, Dict
 31from bs4 import BeautifulSoup, NavigableString
 32from librus_apix.client import Client
 33from librus_apix.helpers import no_access_check
 34from librus_apix.exceptions import ParseError
 35from dataclasses import dataclass
 36
 37
 38@dataclass
 39class Homework:
 40    """
 41    Represents a homework assignment with detailed information.
 42
 43    Attributes:
 44        lesson (str): The lesson or topic associated with the homework.
 45        teacher (str): The name of the teacher who assigned the homework.
 46        subject (str): The subject for which the homework is assigned.
 47        category (str): The category or type of homework (e.g., assignment, project).
 48        task_date (str): The date when the homework was assigned.
 49        completion_date (str): The date by which the homework needs to be completed.
 50        href (str): A URL suffix or link associated with the homework for more details.
 51    """
 52
 53    lesson: str
 54    teacher: str
 55    subject: str
 56    category: str
 57    task_date: str
 58    completion_date: str
 59    href: str
 60
 61
 62def _sanitize_onclick_href(onclick: str) -> str:
 63    href = onclick.split("'")
 64    if len(href) < 2:
 65        return ""
 66
 67    href = href[1].split("/")
 68    if len(href) < 4:
 69        return ""
 70    return href[3]
 71
 72
 73def homework_detail(client: Client, detail_url: str) -> Dict[str, str]:
 74    """
 75    Fetches and parses detailed information about a specific homework assignment.
 76
 77    Args:
 78        client (Client): The client object used to interact with the server.
 79        detail_url (str): The URL suffix to fetch the detailed homework information.
 80
 81    Returns:
 82        Dict[str, str]: A dictionary containing detailed homework information where the keys are detail labels
 83                        and the values are the corresponding detail values.
 84
 85    Raises:
 86        ParseError: If there is an error in parsing the homework details.
 87    """
 88    h_desc = {}
 89    soup = no_access_check(
 90        BeautifulSoup(client.get(client.HOMEWORK_DETAILS_URL + detail_url).text, "lxml")
 91    )
 92    div = soup.find("div", attrs={"class": "container-background"})
 93    if div is None or isinstance(div, NavigableString):
 94        raise ParseError("Error in parsing Homework details.")
 95    line = div.find_all("tr", attrs={"class": ["line0", "line1"]})
 96    for td in line:
 97        pair = td.find_all("td")
 98        if len(pair) < 2:
 99            continue
100        h_desc[pair[0].text.replace("\xa0", " ")] = pair[1].text.replace("\xa0", " ")
101    return h_desc
102
103
104def get_homework(client: Client, date_from: str, date_to: str) -> List[Homework]:
105    """
106    Fetches and parses the list of homework assignments within a specified date range.
107
108    Args:
109        client (Client): The client object used to interact with the server.
110        date_from (str): The start date for fetching homework assignments (format: 'YYYY-MM-DD').
111        date_to (str): The end date for fetching homework assignments (format: 'YYYY-MM-DD').
112
113    Returns:
114        List[Homework]: A list of Homework objects representing the homework assignments within the specified date range.
115
116    Raises:
117        ParseError: If there is an error in parsing the homework assignments.
118    """
119    soup_base = no_access_check(
120        BeautifulSoup(
121            client.post(
122                client.HOMEWORK_URL,
123                data={
124                    "dataOd": date_from,
125                    "dataDo": date_to,
126                    "przedmiot": "-1",
127                    "status": "-1",
128                },
129            ).text,
130            "lxml",
131        )
132    )
133    soup = soup_base.find("table", attrs={"class": "decorated myHomeworkTable"})
134    if soup is None or isinstance(soup, NavigableString):
135        # no proper content found - error or no data
136        soup = soup_base.find("p", attrs={"class": "msgEmptyTable"})
137        if soup is not None:
138            # empty table found - return empty list
139            return []
140        # parsing error
141        raise ParseError("Error in parsing homework.")
142    hw = []
143    lines = soup.find_all("tr", attrs={"class": ["line0", "line1"]})
144    for line in lines:
145        hw_list = [txt.text.replace("\n", "") for txt in line.find_all("td")]
146        if len(hw_list) < 8:
147            raise ParseError(
148                "Error while parsing homework data. homework has less than 8 elements"
149            )
150        href = line.find("input")
151        onclick = href.attrs.get("onclick", "") if line is not None else ""
152        href = _sanitize_onclick_href(onclick)
153        h = Homework(
154            hw_list[0],
155            hw_list[1],
156            hw_list[2],
157            hw_list[3],
158            str(hw_list[4] + " " + hw_list[5]),
159            str(hw_list[6] + " " + hw_list[7]),
160            href,
161        )
162        hw.append(h)
163    return hw
@dataclass
class Homework:
39@dataclass
40class Homework:
41    """
42    Represents a homework assignment with detailed information.
43
44    Attributes:
45        lesson (str): The lesson or topic associated with the homework.
46        teacher (str): The name of the teacher who assigned the homework.
47        subject (str): The subject for which the homework is assigned.
48        category (str): The category or type of homework (e.g., assignment, project).
49        task_date (str): The date when the homework was assigned.
50        completion_date (str): The date by which the homework needs to be completed.
51        href (str): A URL suffix or link associated with the homework for more details.
52    """
53
54    lesson: str
55    teacher: str
56    subject: str
57    category: str
58    task_date: str
59    completion_date: str
60    href: str

Represents a homework assignment with detailed information.

Attributes: lesson (str): The lesson or topic associated with the homework. teacher (str): The name of the teacher who assigned the homework. subject (str): The subject for which the homework is assigned. category (str): The category or type of homework (e.g., assignment, project). task_date (str): The date when the homework was assigned. completion_date (str): The date by which the homework needs to be completed. href (str): A URL suffix or link associated with the homework for more details.

Homework( lesson: str, teacher: str, subject: str, category: str, task_date: str, completion_date: str, href: str)
lesson: str
teacher: str
subject: str
category: str
task_date: str
completion_date: str
href: str
def homework_detail(client: librus_apix.client.Client, detail_url: str) -> Dict[str, str]:
 74def homework_detail(client: Client, detail_url: str) -> Dict[str, str]:
 75    """
 76    Fetches and parses detailed information about a specific homework assignment.
 77
 78    Args:
 79        client (Client): The client object used to interact with the server.
 80        detail_url (str): The URL suffix to fetch the detailed homework information.
 81
 82    Returns:
 83        Dict[str, str]: A dictionary containing detailed homework information where the keys are detail labels
 84                        and the values are the corresponding detail values.
 85
 86    Raises:
 87        ParseError: If there is an error in parsing the homework details.
 88    """
 89    h_desc = {}
 90    soup = no_access_check(
 91        BeautifulSoup(client.get(client.HOMEWORK_DETAILS_URL + detail_url).text, "lxml")
 92    )
 93    div = soup.find("div", attrs={"class": "container-background"})
 94    if div is None or isinstance(div, NavigableString):
 95        raise ParseError("Error in parsing Homework details.")
 96    line = div.find_all("tr", attrs={"class": ["line0", "line1"]})
 97    for td in line:
 98        pair = td.find_all("td")
 99        if len(pair) < 2:
100            continue
101        h_desc[pair[0].text.replace("\xa0", " ")] = pair[1].text.replace("\xa0", " ")
102    return h_desc

Fetches and parses detailed information about a specific homework assignment.

Args: client (Client): The client object used to interact with the server. detail_url (str): The URL suffix to fetch the detailed homework information.

Returns: Dict[str, str]: A dictionary containing detailed homework information where the keys are detail labels and the values are the corresponding detail values.

Raises: ParseError: If there is an error in parsing the homework details.

def get_homework( client: librus_apix.client.Client, date_from: str, date_to: str) -> List[Homework]:
105def get_homework(client: Client, date_from: str, date_to: str) -> List[Homework]:
106    """
107    Fetches and parses the list of homework assignments within a specified date range.
108
109    Args:
110        client (Client): The client object used to interact with the server.
111        date_from (str): The start date for fetching homework assignments (format: 'YYYY-MM-DD').
112        date_to (str): The end date for fetching homework assignments (format: 'YYYY-MM-DD').
113
114    Returns:
115        List[Homework]: A list of Homework objects representing the homework assignments within the specified date range.
116
117    Raises:
118        ParseError: If there is an error in parsing the homework assignments.
119    """
120    soup_base = no_access_check(
121        BeautifulSoup(
122            client.post(
123                client.HOMEWORK_URL,
124                data={
125                    "dataOd": date_from,
126                    "dataDo": date_to,
127                    "przedmiot": "-1",
128                    "status": "-1",
129                },
130            ).text,
131            "lxml",
132        )
133    )
134    soup = soup_base.find("table", attrs={"class": "decorated myHomeworkTable"})
135    if soup is None or isinstance(soup, NavigableString):
136        # no proper content found - error or no data
137        soup = soup_base.find("p", attrs={"class": "msgEmptyTable"})
138        if soup is not None:
139            # empty table found - return empty list
140            return []
141        # parsing error
142        raise ParseError("Error in parsing homework.")
143    hw = []
144    lines = soup.find_all("tr", attrs={"class": ["line0", "line1"]})
145    for line in lines:
146        hw_list = [txt.text.replace("\n", "") for txt in line.find_all("td")]
147        if len(hw_list) < 8:
148            raise ParseError(
149                "Error while parsing homework data. homework has less than 8 elements"
150            )
151        href = line.find("input")
152        onclick = href.attrs.get("onclick", "") if line is not None else ""
153        href = _sanitize_onclick_href(onclick)
154        h = Homework(
155            hw_list[0],
156            hw_list[1],
157            hw_list[2],
158            hw_list[3],
159            str(hw_list[4] + " " + hw_list[5]),
160            str(hw_list[6] + " " + hw_list[7]),
161            href,
162        )
163        hw.append(h)
164    return hw

Fetches and parses the list of homework assignments within a specified date range.

Args: client (Client): The client object used to interact with the server. date_from (str): The start date for fetching homework assignments (format: 'YYYY-MM-DD'). date_to (str): The end date for fetching homework assignments (format: 'YYYY-MM-DD').

Returns: List[Homework]: A list of Homework objects representing the homework assignments within the specified date range.

Raises: ParseError: If there is an error in parsing the homework assignments.