async-bakalari-api 0.3__tar.gz → 0.3.2__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.
Files changed (28) hide show
  1. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/PKG-INFO +32 -1
  2. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/README.md +18 -0
  3. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/pyproject.toml +2 -2
  4. async_bakalari_api-0.3.2/requirements.txt +36 -0
  5. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/src/async_bakalari_api.egg-info/PKG-INFO +32 -1
  6. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/src/async_bakalari_api.egg-info/SOURCES.txt +2 -0
  7. async_bakalari_api-0.3.2/src/async_bakalari_api.egg-info/requires.txt +13 -0
  8. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/src/bakalari_api/bakalari.py +28 -15
  9. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/src/bakalari_api/bakalari_demo.py +86 -17
  10. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/src/bakalari_api/datastructure.py +73 -5
  11. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/src/bakalari_api/komens.py +84 -14
  12. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/tests/test_bakalari.py +98 -18
  13. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/tests/test_datastructure.py +104 -8
  14. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/tests/test_komens.py +140 -28
  15. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/LICENSE.md +0 -0
  16. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/setup.cfg +0 -0
  17. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/src/__init__.py +0 -0
  18. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/src/async_bakalari_api.egg-info/dependency_links.txt +0 -0
  19. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/src/async_bakalari_api.egg-info/entry_points.txt +0 -0
  20. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/src/async_bakalari_api.egg-info/not-zip-safe +0 -0
  21. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/src/async_bakalari_api.egg-info/top_level.txt +0 -0
  22. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/src/bakalari_api/__init__.py +0 -0
  23. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/src/bakalari_api/__main__.py +0 -0
  24. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/src/bakalari_api/const.py +0 -0
  25. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/src/bakalari_api/exceptions.py +0 -0
  26. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/src/bakalari_api/first_login.py +0 -0
  27. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/src/bakalari_api/logger_api.py +0 -0
  28. {async_bakalari_api-0.3 → async_bakalari_api-0.3.2}/tests/test_const.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: async_bakalari_api
3
- Version: 0.3
3
+ Version: 0.3.2
4
4
  Summary: Async API for Bakalari endpoint v3
5
5
  Author-email: "Lukas Svoboda (@schizza)" <opensource@schizza.cz>
6
6
  Maintainer-email: Lukas Svoboda <opensource@schizza.cz>
@@ -219,6 +219,19 @@ Classifier: Programming Language :: Python
219
219
  Requires-Python: >=3.12
220
220
  Description-Content-Type: text/markdown
221
221
  License-File: LICENSE.md
222
+ Requires-Dist: aiofiles==23.2.1
223
+ Requires-Dist: aiohttp==3.9.5
224
+ Requires-Dist: aiosignal==1.3.1
225
+ Requires-Dist: attrs==23.2.0
226
+ Requires-Dist: frozenlist==1.4.1
227
+ Requires-Dist: idna==3.7
228
+ Requires-Dist: logger==1.4
229
+ Requires-Dist: multidict==6.0.5
230
+ Requires-Dist: orjson==3.10.3
231
+ Requires-Dist: python-dateutil==2.9.0.post0
232
+ Requires-Dist: six==1.16.0
233
+ Requires-Dist: strenum==0.4.15
234
+ Requires-Dist: yarl==1.9.4
222
235
 
223
236
  [![codecov](https://codecov.io/gh/schizza/async-bakalari-api3/graph/badge.svg?token=KC2WYAOLOP)](https://codecov.io/gh/schizza/async-bakalari-api3)
224
237
 
@@ -228,6 +241,21 @@ All notable changes to this project will be documented in this file.
228
241
 
229
242
  🇨🇿 Full documentation (czech) on [this site](https://async-bakalari-api.schizza.cz)
230
243
 
244
+ ## [0.3.1]
245
+
246
+ ### Added
247
+
248
+ - `Schools` now support operations with towns
249
+ - new data structure `UniqueTowns` that hold all town names
250
+ - `get_town_partial_name` returns list of the towns based on partial name
251
+ - `get_all_towns returns` list of all towns
252
+ - `istown` checks if the town is present in the list
253
+ - `count_towns` returns number of towns in list
254
+
255
+ ### Changed
256
+
257
+ dependency list is divided to application dependencies and development dependencies
258
+
231
259
  ## [0.3]
232
260
 
233
261
  ### Added
@@ -289,4 +317,7 @@ All notable changes to this project will be documented in this file.
289
317
  - cache list of schools by saving and loading list in JSON format
290
318
 
291
319
  [unreleased]: https://github.com/schizza/bakalari-api3/compare/v0.0.1...HEAD
320
+ [0.3.1]: https://https://github.com/schizza/bakalari-api3/releases/tag/0.3.1
321
+ [0.3]: https://https://github.com/schizza/bakalari-api3/releases/tag/0.3
322
+ [0.2]: https://github.com/schizza/bakalari-api3/releases/tag/0.2
292
323
  [0.0.1]: https://github.com/schizza/bakalari-api3/releases/tag/v0.0.1
@@ -6,6 +6,21 @@ All notable changes to this project will be documented in this file.
6
6
 
7
7
  🇨🇿 Full documentation (czech) on [this site](https://async-bakalari-api.schizza.cz)
8
8
 
9
+ ## [0.3.1]
10
+
11
+ ### Added
12
+
13
+ - `Schools` now support operations with towns
14
+ - new data structure `UniqueTowns` that hold all town names
15
+ - `get_town_partial_name` returns list of the towns based on partial name
16
+ - `get_all_towns returns` list of all towns
17
+ - `istown` checks if the town is present in the list
18
+ - `count_towns` returns number of towns in list
19
+
20
+ ### Changed
21
+
22
+ dependency list is divided to application dependencies and development dependencies
23
+
9
24
  ## [0.3]
10
25
 
11
26
  ### Added
@@ -67,4 +82,7 @@ All notable changes to this project will be documented in this file.
67
82
  - cache list of schools by saving and loading list in JSON format
68
83
 
69
84
  [unreleased]: https://github.com/schizza/bakalari-api3/compare/v0.0.1...HEAD
85
+ [0.3.1]: https://https://github.com/schizza/bakalari-api3/releases/tag/0.3.1
86
+ [0.3]: https://https://github.com/schizza/bakalari-api3/releases/tag/0.3
87
+ [0.2]: https://github.com/schizza/bakalari-api3/releases/tag/0.2
70
88
  [0.0.1]: https://github.com/schizza/bakalari-api3/releases/tag/v0.0.1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "async_bakalari_api"
7
- version = "0.3"
7
+ version = "0.3.2"
8
8
  dynamic = ["dependencies"]
9
9
 
10
10
 
@@ -26,7 +26,7 @@ classifiers = [
26
26
  ]
27
27
 
28
28
  [tool.setuptools.dynamic]
29
- dependencies = { file = ["requirements.in"] }
29
+ dependencies = { file = ["requirements.txt"] }
30
30
 
31
31
  [tool.setuptools]
32
32
  platforms = ["any"]
@@ -0,0 +1,36 @@
1
+ #
2
+ # This file is autogenerated by pip-compile with Python 3.12
3
+ # by the following command:
4
+ #
5
+ # pip-compile
6
+ #
7
+ aiofiles==23.2.1
8
+ # via -r requirements.in
9
+ aiohttp==3.9.5
10
+ # via -r requirements.in
11
+ aiosignal==1.3.1
12
+ # via aiohttp
13
+ attrs==23.2.0
14
+ # via aiohttp
15
+ frozenlist==1.4.1
16
+ # via
17
+ # aiohttp
18
+ # aiosignal
19
+ idna==3.7
20
+ # via yarl
21
+ logger==1.4
22
+ # via -r requirements.in
23
+ multidict==6.0.5
24
+ # via
25
+ # aiohttp
26
+ # yarl
27
+ orjson==3.10.3
28
+ # via -r requirements.in
29
+ python-dateutil==2.9.0.post0
30
+ # via -r requirements.in
31
+ six==1.16.0
32
+ # via python-dateutil
33
+ strenum==0.4.15
34
+ # via -r requirements.in
35
+ yarl==1.9.4
36
+ # via aiohttp
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: async_bakalari_api
3
- Version: 0.3
3
+ Version: 0.3.2
4
4
  Summary: Async API for Bakalari endpoint v3
5
5
  Author-email: "Lukas Svoboda (@schizza)" <opensource@schizza.cz>
6
6
  Maintainer-email: Lukas Svoboda <opensource@schizza.cz>
@@ -219,6 +219,19 @@ Classifier: Programming Language :: Python
219
219
  Requires-Python: >=3.12
220
220
  Description-Content-Type: text/markdown
221
221
  License-File: LICENSE.md
222
+ Requires-Dist: aiofiles==23.2.1
223
+ Requires-Dist: aiohttp==3.9.5
224
+ Requires-Dist: aiosignal==1.3.1
225
+ Requires-Dist: attrs==23.2.0
226
+ Requires-Dist: frozenlist==1.4.1
227
+ Requires-Dist: idna==3.7
228
+ Requires-Dist: logger==1.4
229
+ Requires-Dist: multidict==6.0.5
230
+ Requires-Dist: orjson==3.10.3
231
+ Requires-Dist: python-dateutil==2.9.0.post0
232
+ Requires-Dist: six==1.16.0
233
+ Requires-Dist: strenum==0.4.15
234
+ Requires-Dist: yarl==1.9.4
222
235
 
223
236
  [![codecov](https://codecov.io/gh/schizza/async-bakalari-api3/graph/badge.svg?token=KC2WYAOLOP)](https://codecov.io/gh/schizza/async-bakalari-api3)
224
237
 
@@ -228,6 +241,21 @@ All notable changes to this project will be documented in this file.
228
241
 
229
242
  🇨🇿 Full documentation (czech) on [this site](https://async-bakalari-api.schizza.cz)
230
243
 
244
+ ## [0.3.1]
245
+
246
+ ### Added
247
+
248
+ - `Schools` now support operations with towns
249
+ - new data structure `UniqueTowns` that hold all town names
250
+ - `get_town_partial_name` returns list of the towns based on partial name
251
+ - `get_all_towns returns` list of all towns
252
+ - `istown` checks if the town is present in the list
253
+ - `count_towns` returns number of towns in list
254
+
255
+ ### Changed
256
+
257
+ dependency list is divided to application dependencies and development dependencies
258
+
231
259
  ## [0.3]
232
260
 
233
261
  ### Added
@@ -289,4 +317,7 @@ All notable changes to this project will be documented in this file.
289
317
  - cache list of schools by saving and loading list in JSON format
290
318
 
291
319
  [unreleased]: https://github.com/schizza/bakalari-api3/compare/v0.0.1...HEAD
320
+ [0.3.1]: https://https://github.com/schizza/bakalari-api3/releases/tag/0.3.1
321
+ [0.3]: https://https://github.com/schizza/bakalari-api3/releases/tag/0.3
322
+ [0.2]: https://github.com/schizza/bakalari-api3/releases/tag/0.2
292
323
  [0.0.1]: https://github.com/schizza/bakalari-api3/releases/tag/v0.0.1
@@ -1,12 +1,14 @@
1
1
  LICENSE.md
2
2
  README.md
3
3
  pyproject.toml
4
+ requirements.txt
4
5
  src/__init__.py
5
6
  src/async_bakalari_api.egg-info/PKG-INFO
6
7
  src/async_bakalari_api.egg-info/SOURCES.txt
7
8
  src/async_bakalari_api.egg-info/dependency_links.txt
8
9
  src/async_bakalari_api.egg-info/entry_points.txt
9
10
  src/async_bakalari_api.egg-info/not-zip-safe
11
+ src/async_bakalari_api.egg-info/requires.txt
10
12
  src/async_bakalari_api.egg-info/top_level.txt
11
13
  src/bakalari_api/__init__.py
12
14
  src/bakalari_api/__main__.py
@@ -0,0 +1,13 @@
1
+ aiofiles==23.2.1
2
+ aiohttp==3.9.5
3
+ aiosignal==1.3.1
4
+ attrs==23.2.0
5
+ frozenlist==1.4.1
6
+ idna==3.7
7
+ logger==1.4
8
+ multidict==6.0.5
9
+ orjson==3.10.3
10
+ python-dateutil==2.9.0.post0
11
+ six==1.16.0
12
+ strenum==0.4.15
13
+ yarl==1.9.4
@@ -51,10 +51,14 @@ class Bakalari:
51
51
  self.auto_cache_credentials = auto_cache_credentials
52
52
  self.cache_filename = cache_filename
53
53
  self.session = aiohttp.ClientSession()
54
+ self.schools = Schools()
54
55
 
55
56
  if self.auto_cache_credentials and not self.cache_filename:
56
57
  raise Ex.CacheError("Auto-cache is enabled, but no filename is provided!")
57
58
 
59
+ if self.auto_cache_credentials and self.cache_filename:
60
+ self.load_credentials(self.cache_filename)
61
+
58
62
  def __del__(self):
59
63
  """Destructor."""
60
64
  # Close connection when this object is destroyed
@@ -187,11 +191,9 @@ class Bakalari:
187
191
  log.debug("Requesting URL %s, kwargs: %s", url, kwargs)
188
192
  try:
189
193
  async with asyncio.timeout(REQUEST_TIMEOUT):
190
-
191
194
  async with session(
192
195
  url, ssl=True, headers=headers, **kwargs
193
196
  ) as response:
194
-
195
197
  if (
196
198
  response.headers.get(aiohttp.hdrs.CONTENT_TYPE)
197
199
  == "application/octet-stream"
@@ -250,23 +252,33 @@ class Bakalari:
250
252
  case _:
251
253
  raise Ex.BadRequestException(f"{url} with message: {response_json}")
252
254
 
253
- async def schools_list(self, town: str | None = None) -> Schools:
255
+ async def schools_list(
256
+ self, town: str | None = None, recursive: bool = True
257
+ ) -> Schools:
254
258
  """Return list of schools with their API points."""
255
259
 
256
260
  _schools_list = Schools()
257
261
  headers = {"Accept": "application/json"}
258
262
 
259
- if not town:
260
- log.debug("Gathering list of towns ...")
261
- try:
262
- towns_json = await self.send_unauth_request(
263
- EndPoint.SCHOOL_LIST, headers
264
- )
265
- except Exception as exc:
266
- log.error(f"Error while gathering schools endpoints. {exc}")
267
- return None
268
- else:
269
- towns_json: dict = [{"name": f"{town}"}]
263
+ log.debug("Gathering list of towns ...")
264
+ try:
265
+ towns_json = await self.send_unauth_request(EndPoint.SCHOOL_LIST, headers)
266
+ except Exception as exc:
267
+ log.error(f"Error while gathering schools endpoints. {exc}")
268
+ return None
269
+
270
+ if town and recursive:
271
+ towns_json = [
272
+ town_element
273
+ for town_element in towns_json
274
+ if town in town_element["name"]
275
+ ]
276
+ if town and not recursive:
277
+ towns_json = [
278
+ town_element
279
+ for town_element in towns_json
280
+ if town_element["name"].startswith(town)
281
+ ]
270
282
 
271
283
  schools: list = []
272
284
  tasks = []
@@ -289,7 +301,6 @@ class Bakalari:
289
301
 
290
302
  responses = await asyncio.gather(*tasks)
291
303
  for response_town in responses:
292
-
293
304
  schools: dict = response_town
294
305
  for _schools in schools.get("schools"):
295
306
  _schools_list.append_school(
@@ -298,6 +309,8 @@ class Bakalari:
298
309
  town=response_town.get("name"),
299
310
  )
300
311
 
312
+ self.schools = _schools_list
313
+
301
314
  return _schools_list
302
315
 
303
316
  async def first_login(self, username: str, password: str) -> Credentials:
@@ -2,25 +2,29 @@
2
2
 
3
3
  import argparse
4
4
  import asyncio
5
+ import os
5
6
 
7
+ import aiofiles
6
8
  from logger import logging
7
9
  import orjson
8
10
 
9
11
  from .bakalari import Bakalari, Schools
10
- from .komens import Komens
12
+ from .komens import Komens, MessageContainer
11
13
  from .logger_api import api_logger
12
14
 
13
15
 
14
- def w(name, data):
16
+ async def w(name, data):
15
17
  """Write JSON data to file."""
16
- with open(name, "+wb") as fi:
17
- fi.write(orjson.dumps(data, option=orjson.OPT_INDENT_2))
18
+ async with aiofiles.open(name, "+wb") as fi:
19
+ await fi.write(orjson.dumps(data, option=orjson.OPT_INDENT_2))
20
+ await fi.flush()
18
21
 
19
22
 
20
- def wb(name, data):
23
+ async def wb(name, data):
21
24
  """Write data to file."""
22
- with open(name, "wb") as fi:
23
- fi.write(data)
25
+ async with aiofiles.open(name, "wb") as fi:
26
+ await fi.write(data)
27
+ await fi.flush()
24
28
 
25
29
 
26
30
  def r(name):
@@ -65,26 +69,78 @@ async def schools(args, bakalari: Bakalari):
65
69
 
66
70
  async def komens(args, bakalari):
67
71
  """Komens command."""
72
+
73
+ async def create_attachment_task(message: MessageContainer):
74
+ """Create a task for saving an attachment."""
75
+ tasks = []
76
+ if args.komens_save_attachment:
77
+ if message.isattachments():
78
+ for att in message.attachments:
79
+ task = asyncio.create_task(
80
+ wb(*(await Komens(bakalari=bakalari).get_attachment(att.id)))
81
+ )
82
+ tasks.append(task)
83
+ return tasks
84
+
85
+ async def msgs(messages):
86
+ """Print messages and save attachments if needed."""
87
+ tasks = []
88
+ for msg in messages:
89
+ print(str(msg))
90
+ tasks = create_attachment_task(msg)
91
+
92
+ asyncio.gather(*tasks)
93
+
94
+ async def msgs_w(messages):
95
+ """Save messages and attachments if needed."""
96
+ tasks = []
97
+
98
+ if isinstance(messages, MessageContainer):
99
+ await wb(args.komens_save, messages.as_json())
100
+ tasks.extend(await create_attachment_task(messages))
101
+
102
+ if isinstance(messages, list):
103
+ for msg in messages:
104
+ await wb(f"{args.komens_save}_{msg.mid}.json", msg.as_json())
105
+ tasks.extend(await create_attachment_task(msg))
106
+
107
+ await asyncio.gather(*tasks)
108
+
68
109
  if args.komens_list:
69
- print(await Komens(bakalari=bakalari).fetch_messages())
110
+ if not args.komens_unread:
111
+ await msgs(await Komens(bakalari=bakalari).fetch_messages())
112
+ else:
113
+ await msgs(await Komens(bakalari=bakalari).get_unread_messages())
114
+
70
115
  if args.extend:
71
116
  messages = await Komens(bakalari=bakalari).fetch_messages()
72
- print(messages.get_message_by_id(args.extend))
117
+ msgs([messages.get_message_by_id(args.extend)])
118
+
73
119
  if args.komens_save:
74
- messages = await Komens(bakalari=bakalari).fetch_messages()
75
- w(args.komens_save, messages.json())
120
+ if not args.komens_unread:
121
+ await msgs_w(await Komens(bakalari=bakalari).fetch_messages())
122
+ else:
123
+ await msgs_w(await Komens(bakalari=bakalari).get_unread_messages())
124
+
76
125
  if args.attachment:
77
- wb(*(await Komens(bakalari=bakalari).get_attachment(args.attachment)))
126
+ await wb(*(await Komens(bakalari=bakalari).get_attachment(args.attachment)))
78
127
 
79
128
 
80
129
  async def runme(args):
81
130
  """Run the main function."""
82
131
 
83
132
  if args.sf:
84
- schools: Schools = await Schools().load_from_file(args.sf)
133
+ try:
134
+ schools: Schools = await Schools().load_from_file(args.sf)
135
+ except Exception as ex:
136
+ os._exit(ex)
85
137
  else:
86
138
  schools: Schools = await Bakalari().schools_list(town=args.town)
87
139
 
140
+ if not schools:
141
+ print("Nenalezeny žádné školy")
142
+ os._exit(1)
143
+
88
144
  school = args.school
89
145
  if school:
90
146
  server = schools.get_url(school)
@@ -245,9 +301,18 @@ def main() -> None:
245
301
 
246
302
  komens_action = komens_parser.add_mutually_exclusive_group()
247
303
  komens_parser.add_argument(
248
- "--messages",
304
+ "-u",
305
+ "--unread",
306
+ help="Vypíše nepřečtené zprávy",
307
+ dest="komens_unread",
308
+ action="store_true",
309
+ )
310
+ komens_parser.add_argument(
311
+ "-sa",
312
+ "--save_attachment",
249
313
  action="store_true",
250
- help="Načte zprávy z Komens",
314
+ help="Uloží automaticky přílohy zpráv do souboru",
315
+ dest="komens_save_attachment",
251
316
  )
252
317
  komens_action.add_argument(
253
318
  "-l",
@@ -256,6 +321,7 @@ def main() -> None:
256
321
  dest="komens_list",
257
322
  action="store_true",
258
323
  )
324
+
259
325
  komens_action.add_argument(
260
326
  "-e",
261
327
  "--extend",
@@ -279,6 +345,9 @@ def main() -> None:
279
345
  args = parser.parse_args()
280
346
 
281
347
  if args.verbose:
282
- api_logger("Bakalari API").get().setLevel(logging.DEBUG)
348
+ log = api_logger("Bakalari API", loglevel=logging.DEBUG).get()
349
+ else:
350
+ log = api_logger("Bakalari API").get()
283
351
 
284
- asyncio.run(runme(args))
352
+ loop = asyncio.get_event_loop()
353
+ loop.run_until_complete(runme(args))
@@ -54,6 +54,49 @@ class School:
54
54
  town: str = None
55
55
 
56
56
 
57
+ class UniqueTowns:
58
+ """Unique towns list."""
59
+
60
+ def __init__(self) -> None:
61
+ """Create unique towns list."""
62
+
63
+ self.list: list[str] = []
64
+ self.set: set[str] = set()
65
+
66
+ def append(self, town: str) -> None:
67
+ """Append new town to the list."""
68
+
69
+ if town not in self.set:
70
+ self.list.append(town)
71
+ self.set.add(town)
72
+
73
+ def __str__(self) -> str:
74
+ """Return string representation of the list."""
75
+ return str(self.list)
76
+
77
+ def __len__(self) -> int:
78
+ """Return number of towns in the list."""
79
+ return len(self.list)
80
+
81
+ def __iter__(self):
82
+ """Return iterator for the list."""
83
+ return iter(self.list)
84
+
85
+ def __contains__(self, value: str) -> bool:
86
+ """Check if town is in the list."""
87
+ return value in self.set
88
+
89
+ def __delitem__(self, value: str) -> None:
90
+ """Remove town from the list."""
91
+ if value in self.set:
92
+ self.list.remove(value)
93
+ self.set.remove(value)
94
+
95
+ def __getitem__(self, index: int) -> str:
96
+ """Get town by index."""
97
+ return self.list[index]
98
+
99
+
57
100
  class Schools:
58
101
  """List of schools with their url for Bakalari API."""
59
102
 
@@ -61,6 +104,11 @@ class Schools:
61
104
  """List of schools with their url for Bakalari API."""
62
105
 
63
106
  self.school_list: list[School] = []
107
+ self.towns_list: UniqueTowns = UniqueTowns()
108
+
109
+ def __len__(self) -> int:
110
+ """Return number of schools in the list."""
111
+ return len(self.school_list)
64
112
 
65
113
  def append_school(
66
114
  self,
@@ -88,11 +136,27 @@ class Schools:
88
136
  )
89
137
  return False
90
138
 
91
- new_school = School(name=name, api_point=api_point, town=town)
92
- self.school_list.append(new_school)
139
+ self.school_list.append(School(name=name, api_point=api_point, town=town))
140
+ self.towns_list.append(town)
93
141
 
94
142
  return True
95
143
 
144
+ def get_all_towns(self) -> list[str]:
145
+ """Return list of all towns in the list."""
146
+ return self.towns_list.list
147
+
148
+ def istown(self, town: str) -> bool:
149
+ """Check if town is in the list."""
150
+ return town in self.towns_list
151
+
152
+ def get_towns_partial_name(self, partial: str) -> list[str]:
153
+ """Get town by partial name."""
154
+ return [town for town in self.towns_list if partial in town]
155
+
156
+ def count_towns(self) -> int:
157
+ """Return number of towns in the list."""
158
+ return len(self.towns_list)
159
+
96
160
  def get_url(self, name: str | None = None, idx: int | None = None) -> str | False:
97
161
  """Return url for school from name or index in dictionary.
98
162
 
@@ -123,7 +187,9 @@ class Schools:
123
187
  def get_school_name_by_api_point(self, api_point: str) -> str | bool:
124
188
  """Get school name by its api point."""
125
189
  with suppress(IndexError):
126
- return [item for item in self.school_list if api_point == item.api_point][0].name
190
+ return [item for item in self.school_list if api_point == item.api_point][
191
+ 0
192
+ ].name
127
193
 
128
194
  def save_to_file(self, filename: str) -> bool:
129
195
  """Save loaded school list to file in JSON format."""
@@ -142,7 +208,9 @@ class Schools:
142
208
  with open(filename, "wb") as file:
143
209
  file.write(orjson.dumps(self.school_list, option=orjson.OPT_INDENT_2))
144
210
  except (OSError, orjson.JSONEncodeError) as ex:
145
- log.error(f"Unable to save schools list to file {filename}. Error: {str(ex)}")
211
+ log.error(
212
+ f"Unable to save schools list to file {filename}. Error: {str(ex)}"
213
+ )
146
214
  return False
147
215
 
148
216
  return True
@@ -153,8 +221,8 @@ class Schools:
153
221
  try:
154
222
  with open(filename, mode="+rb") as file:
155
223
  data = orjson.loads(file.read())
156
- file.close()
157
224
  except OSError:
225
+ log.error(f"Unable to open file {filename}.")
158
226
  return False
159
227
  except orjson.JSONDecodeError:
160
228
  log.error(f"Unable to decode JSON file. File {filename} is corrupted.")