mosdiary 0.3.2__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mosdiary
3
- Version: 0.3.2
3
+ Version: 0.4.0
4
4
  Summary: Неофициальная асинхронная библиотека для работы с API школьного дневника МЭШ
5
5
  Author-email: vra000 <voronin.a.romanvra@mail.ru>
6
6
  License-Expression: GPL-3.0-only
@@ -7,7 +7,7 @@ from io import BytesIO
7
7
  from re import DOTALL, IGNORECASE, search
8
8
  from time import time
9
9
  from types import TracebackType
10
- from typing import Literal, TypeVar
10
+ from typing import Literal, Optional, TypeVar
11
11
 
12
12
  from aiohttp import (
13
13
  ClientError,
@@ -17,7 +17,7 @@ from aiohttp import (
17
17
  ClientSession,
18
18
  ClientSSLError,
19
19
  ContentTypeError,
20
- ServerFingerprintMismatch,
20
+ ServerFingerprintMismatch
21
21
  )
22
22
  from pydantic import BaseModel
23
23
  from yarl import URL
@@ -38,13 +38,14 @@ from .exceptions import (
38
38
  TokenExpired,
39
39
  TwoFactorRequiredException,
40
40
  VerificationAttemptsExhaustedException,
41
- VerificationCodeExpiredException,
41
+ VerificationCodeExpiredException
42
42
  )
43
43
  from .enums import ScheduleEventType
44
44
  from .types.profile import UserInfo, Family, ProfileDeatail
45
45
  from .types.homework import Homework
46
46
  from .types.marks import Mark, SubjectMark
47
47
  from .types.lessons import LessonDay
48
+ from .types.study_class import StudyClass
48
49
  from .types.schedule_events import ScheduleEvent, parse_schedule_event
49
50
 
50
51
 
@@ -186,18 +187,18 @@ class MOSDiaryClient:
186
187
  self,
187
188
  method: Literal['GET', 'POST'],
188
189
  endpoint: str,
189
- return_type: Literal['dict', 'response', 'bool', 'text'] = 'dict',
190
+ return_type: Literal['dict', 'response', 'bool'] = 'dict',
190
191
  use_auth: bool = True,
191
192
  **kwargs,
192
- ) -> dict | ClientResponse | bool | str:
193
+ ) -> dict | list | ClientResponse | bool:
193
194
  """Отправить HTTP-запрос к API МЭШ.
194
195
 
195
196
  Returns:
196
- dict | ClientResponse | bool | str: JSON-объект, необработанный
197
- ответ, признак успешного статуса или текст ответа - в
198
- зависимости от `return_type`.
197
+ dict | list | ClientResponse | bool: Разобранный JSON (объект или
198
+ массив), необработанный ответ или признак успешного статуса -
199
+ в зависимости от `return_type`.
199
200
  """
200
- if return_type not in ('dict', 'response', 'bool', 'text'):
201
+ if return_type not in ('dict', 'response', 'bool'):
201
202
  raise ValueError(f'Неизвестный тип возврата: {return_type}')
202
203
 
203
204
  url = (
@@ -242,15 +243,12 @@ class MOSDiaryClient:
242
243
  if return_type == 'bool':
243
244
  return 200 <= response.status < 300
244
245
 
245
- if return_type == 'text':
246
- return await response.text()
247
-
248
246
  try:
249
247
  data = await response.json()
250
248
  except (ContentTypeError, ValueError) as error:
251
249
  raise InvalidResponseException('Ответ API не является корректным JSON') from error
252
- if not isinstance(data, dict):
253
- raise InvalidResponseException('Ответ API не является JSON-объектом')
250
+ if not isinstance(data, (dict, list)):
251
+ raise InvalidResponseException('Ответ API не является JSON-объектом или массивом')
254
252
  return data
255
253
  except (ClientSSLError, ServerFingerprintMismatch) as error:
256
254
  raise APIConnectionException('Не удалось установить защищённое соединение с МЭШ') from error
@@ -265,7 +263,7 @@ class MOSDiaryClient:
265
263
  await sleep(0.5 * 2 ** retry_number)
266
264
  retry_number += 1
267
265
  continue
268
- raise APITimeoutException('Истёк тайм-аут запроса к МЭШ') from error
266
+ raise APITimeoutException('Истёк таймаут запроса к МЭШ') from error
269
267
  except ClientError as error:
270
268
  raise APIException('Не удалось выполнить запрос к МЭШ') from error
271
269
 
@@ -278,7 +276,7 @@ class MOSDiaryClient:
278
276
  bool:
279
277
  Выполнен ли запрос успешно
280
278
  """
281
- success = await self._send_request('GET', 'https://school.mos.ru/v3/auth/logout', return_type='bool')
279
+ success = await self._send_request('GET', 'https://school.mos.ru/v3/auth/logout', return_type='bool', allow_redirects=True)
282
280
  if success:
283
281
  self.id = None
284
282
  self.uid = None
@@ -787,13 +785,36 @@ class MOSDiaryClient:
787
785
  """
788
786
  if self.id is None:
789
787
  await self.get_family_info()
790
- response = await self._send_request(
791
- 'GET',
792
- f'family/web/v1/marks?student_id={self.id}&from={from_date}&to={to_date}'
793
- )
788
+ response = await self._send_request('GET', f'family/web/v1/marks?student_id={self.id}&from={from_date}&to={to_date}')
794
789
  return _parse_response_list(
795
790
  response,
796
791
  key='payload',
797
792
  parser=Mark.model_validate,
798
793
  error_message='МЭШ вернул некорректный список оценок'
799
- )
794
+ )
795
+
796
+
797
+ async def get_study_class(self, id: int)-> StudyClass:
798
+ """Получить школьный класс по ID"""
799
+
800
+ return StudyClass.model_validate(await self._send_request('GET', f'ej/core/family/v1/class_units/{id}'))
801
+
802
+
803
+ async def get_study_classes(self, school_id: Optional[int] = None, class_num: Optional[int] = None, mentor_id: Optional[int] = None)-> list[StudyClass]:
804
+ """
805
+ Получить учебные классы во всей школе
806
+ Args:
807
+ school_id (`Optional[int]`): ID школы
808
+ class_num (`Optional[int]`): Номер класса (девятый или восьмой класс)
809
+ mentor_id (`Optional[int]`): ID классного руководителя
810
+ """
811
+
812
+ params = {}
813
+ if school_id is not None:
814
+ params['school_id'] = school_id
815
+ if class_num is not None:
816
+ params['class_level_id'] = class_num
817
+ if mentor_id is not None:
818
+ params['mentor_id'] = mentor_id
819
+
820
+ return [StudyClass.model_validate(study_class) for study_class in await self._send_request('GET', 'ej/core/family/v1/class_units', params=params)]
@@ -12,12 +12,10 @@ class SubjectMark(BaseModel):
12
12
  """Школьная оценка по предмету"""
13
13
  model_config = ConfigDict(extra='ignore')
14
14
 
15
- #TODO: Описать
16
15
  average: Decimal
16
+ """Средний балл за аттестационный период"""
17
17
 
18
- dynamic_type: MarkDynamicType = Field(
19
- validation_alias=AliasChoices('dynamic_type', 'dynamic')
20
- )
18
+ dynamic_type: MarkDynamicType = Field(validation_alias=AliasChoices('dynamic_type', 'dynamic'))
21
19
  """Динамика среднего балла по оценке"""
22
20
 
23
21
  periods: list[SubjectMarkPeriod]
@@ -55,11 +53,11 @@ class SubjectMarkPeriod(BaseModel):
55
53
  count: int
56
54
  """Кол-во оценок"""
57
55
 
58
- target: MarkTarget
56
+ target: MarkTarget | None
59
57
  """Цель текущей оценки до следующего балла"""
60
58
 
61
- #TODO: Описать
62
- fixed_value: Any | None
59
+ fixed_value: int | None
60
+ """Округлённое значение среднего балла"""
63
61
 
64
62
  start_date: date = Field(validation_alias='start_iso')
65
63
  """Дата начала учебного периода"""
@@ -0,0 +1,42 @@
1
+ from pydantic import AliasChoices, BaseModel, ConfigDict, Field, field_validator
2
+ from datetime import date, datetime
3
+ from decimal import Decimal
4
+
5
+
6
+ class StudyClass(BaseModel):
7
+ """Школьный класс"""
8
+ model_config = ConfigDict(extra='ignore')
9
+
10
+ id: int
11
+ """ID школьного класса"""
12
+
13
+ display_name: str | None = None
14
+ """Отображаемое имя класса: *3Б2*"""
15
+
16
+ letter: str | None = None
17
+ """Имя класса без цифры: *Б2*"""
18
+
19
+ school_id: int
20
+ """ID школы"""
21
+
22
+ mentor_ids: list[int] = Field(default_factory=list)
23
+ """ID классных руководителей"""
24
+
25
+ class_level_num: int = Field(validation_alias='class_level_id')
26
+ """Номер класса, *к примеру, 9 класс или 3 класс*"""
27
+
28
+ name: str = Field(validation_alias='name')
29
+ """Полное название класса"""
30
+
31
+ student_cnt: int = Field(validation_alias='student_count')
32
+ """Кол-во учеников в классе"""
33
+
34
+ ae_percentage: float | None = None
35
+ """Доля в % учеников класса, занимающихся дополнительным образованием"""
36
+
37
+ #TODO: Типизировать
38
+ home_based_periods: list = Field(default_factory=list)
39
+ """Периоды домашнего обучения"""
40
+
41
+ home_based: bool
42
+ """Учится ли класс на домашнем обучении"""
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mosdiary
3
- Version: 0.3.2
3
+ Version: 0.4.0
4
4
  Summary: Неофициальная асинхронная библиотека для работы с API школьного дневника МЭШ
5
5
  Author-email: vra000 <voronin.a.romanvra@mail.ru>
6
6
  License-Expression: GPL-3.0-only
@@ -15,4 +15,5 @@ mosdiary/types/homework.py
15
15
  mosdiary/types/lessons.py
16
16
  mosdiary/types/marks.py
17
17
  mosdiary/types/profile.py
18
- mosdiary/types/schedule_events.py
18
+ mosdiary/types/schedule_events.py
19
+ mosdiary/types/study_class.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "mosdiary"
7
- version = "0.3.2"
7
+ version = "0.4.0"
8
8
  description = "Неофициальная асинхронная библиотека для работы с API школьного дневника МЭШ"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
File without changes
File without changes
File without changes
File without changes
File without changes