async-bakalari-api 0.2__tar.gz → 0.3__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 (29) hide show
  1. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/PKG-INFO +54 -37
  2. async_bakalari_api-0.3/README.md +70 -0
  3. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/pyproject.toml +18 -17
  4. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/src/async_bakalari_api.egg-info/PKG-INFO +54 -37
  5. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/src/async_bakalari_api.egg-info/SOURCES.txt +5 -2
  6. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/src/bakalari_api/bakalari.py +95 -37
  7. async_bakalari_api-0.3/src/bakalari_api/bakalari_demo.py +284 -0
  8. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/src/bakalari_api/const.py +6 -1
  9. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/src/bakalari_api/datastructure.py +7 -14
  10. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/src/bakalari_api/komens.py +65 -33
  11. async_bakalari_api-0.3/tests/test_bakalari.py +584 -0
  12. async_bakalari_api-0.3/tests/test_const.py +13 -0
  13. async_bakalari_api-0.3/tests/test_datastructure.py +162 -0
  14. async_bakalari_api-0.3/tests/test_komens.py +221 -0
  15. async_bakalari_api-0.2/README.md +0 -45
  16. async_bakalari_api-0.2/src/async_bakalari_api.egg-info/requires.txt +0 -8
  17. async_bakalari_api-0.2/src/bakalari_api/bakalari_demo.py +0 -53
  18. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/LICENSE.md +0 -0
  19. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/setup.cfg +0 -0
  20. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/src/__init__.py +0 -0
  21. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/src/async_bakalari_api.egg-info/dependency_links.txt +0 -0
  22. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/src/async_bakalari_api.egg-info/entry_points.txt +0 -0
  23. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/src/async_bakalari_api.egg-info/not-zip-safe +0 -0
  24. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/src/async_bakalari_api.egg-info/top_level.txt +0 -0
  25. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/src/bakalari_api/__init__.py +0 -0
  26. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/src/bakalari_api/__main__.py +0 -0
  27. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/src/bakalari_api/exceptions.py +0 -0
  28. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/src/bakalari_api/first_login.py +0 -0
  29. {async_bakalari_api-0.2 → async_bakalari_api-0.3}/src/bakalari_api/logger_api.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: async_bakalari_api
3
- Version: 0.2
3
+ Version: 0.3
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>
@@ -208,7 +208,7 @@ License:
208
208
  limitations under the License.
209
209
 
210
210
  Project-URL: Homepage, https://github.com/schizza/bakalari-api3
211
- Project-URL: Documentation, https://github.com/schizza/bakalari-api3
211
+ Project-URL: Documentation, https://async-bakalari-api.schizza.cz
212
212
  Project-URL: Repository, https://github.com/schizza/bakalari-api3
213
213
  Project-URL: Bug Tracker, https://github.com/schizza/bakalari-api3/issues
214
214
  Project-URL: Changelog, https://github.com/schizza/bakalari-api3/blob/master/CHANGELOG.md
@@ -219,57 +219,74 @@ 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: asyncio
223
- Requires-Dist: typing
224
- Requires-Dist: aiohttp
225
- Requires-Dist: orjson
226
- Requires-Dist: async_timeout
227
- Requires-Dist: logger
228
- Requires-Dist: strenum
229
- Requires-Dist: pytest
230
222
 
231
223
  [![codecov](https://codecov.io/gh/schizza/async-bakalari-api3/graph/badge.svg?token=KC2WYAOLOP)](https://codecov.io/gh/schizza/async-bakalari-api3)
232
224
 
233
- # Python async client for Bakalari API v3
225
+ # Changelog
234
226
 
235
- ### 0.0.2
227
+ All notable changes to this project will be documented in this file.
236
228
 
237
- ## Added
229
+ 🇨🇿 Full documentation (czech) on [this site](https://async-bakalari-api.schizza.cz)
238
230
 
239
- * better exceptions handling and logging
240
- * class Komens
241
- * count unread messages
242
- * get all messages
231
+ ## [0.3]
243
232
 
244
- * tests and coverage
233
+ ### Added
245
234
 
246
- ## Changed
235
+ - `bakalari_demo.py` is now CLI application
236
+ - `Komens` now support for downloading attachment - `get_attachment`
237
+ - `send_auth_request` now supports extending EndPoints url wiht `extend` argument
238
+ - `school_list` now supports variable `town` - fetch schools in the town to limit downloading full list of schools.
239
+ - `Messages` class now have function `json` to return messages as JSON representative
240
+ - `Messages` class have `__str__` function for better handling `str(Messages)`
247
241
 
248
- * async_schools_list moved to Bakalari class
249
- * Refactor login functions
250
- * Refactor token handling
242
+ ### Changed
251
243
 
252
- ## Fixed
244
+ - refactor of the code for speed and better reading of the code
245
+ - `school_list` now fetching schools in concurency mode - improved speed form about 1:30 min to 20s
246
+ - `mid` variable in the `MessageContainter` is now string instead of integer.
247
+ - `async_school_list` renamed to `school_list` as all methods are async
248
+ - `MessageContainter` returns JSON bytes on `as_json()` call instead of `orjson.Fragment`
249
+ - `get_messsages()` renamed to `fetch_messages()`
253
250
 
254
- * Invalid refresh token
255
- * Refactor send_request to better maintenance
251
+ ### Removed
256
252
 
257
- ### v0.1
253
+ - `username` from `Credentials` - as we do not need to store it
258
254
 
259
- ## Class School from `datastructure.py`
255
+ ## [0.2]
260
256
 
261
- Now supports to download list of schools with their API points.
257
+ ### Added
262
258
 
263
- * get_url by school name or index in list
264
- * search school by town
265
- * cache list of schools by saving and loading list in JSON format
259
+ - better exceptions handling and logging
260
+ - `class Komens`
261
+ - count unread messages
262
+ - get all messages
263
+ - tests and coverage
266
264
 
267
- ## Class Bakalari
265
+ ### Changed
268
266
 
269
- * first login with username and password and stores access and refresh token
270
- * automaticaly refreshes access token with refresh token if refresh token is not expired
271
- * save access and refresh token localy to be cached
267
+ - `async_schools_list` moved to `Bakalari` class
268
+ - Refactor login functions
269
+ - Refactor token handling
272
270
 
273
- ## Class Komens
271
+ ### Fixed
274
272
 
275
- * count unread messages `count_unread_messages`
273
+ - Invalid refresh token
274
+ - Refactor send_request to better maintenance
275
+
276
+ ## [0.0.1]
277
+
278
+ ### Added
279
+
280
+ - main `class Bakalari`
281
+
282
+ - supports saving `access token` and `refresh token` localy
283
+ - automatically refreshes access token with refresh token if refresh token is not expired
284
+
285
+ - `class Schools` in `datastructures.py` lists all schools with their API points
286
+
287
+ - get_url by school name or index in list
288
+ - search school by town
289
+ - cache list of schools by saving and loading list in JSON format
290
+
291
+ [unreleased]: https://github.com/schizza/bakalari-api3/compare/v0.0.1...HEAD
292
+ [0.0.1]: https://github.com/schizza/bakalari-api3/releases/tag/v0.0.1
@@ -0,0 +1,70 @@
1
+ [![codecov](https://codecov.io/gh/schizza/async-bakalari-api3/graph/badge.svg?token=KC2WYAOLOP)](https://codecov.io/gh/schizza/async-bakalari-api3)
2
+
3
+ # Changelog
4
+
5
+ All notable changes to this project will be documented in this file.
6
+
7
+ 🇨🇿 Full documentation (czech) on [this site](https://async-bakalari-api.schizza.cz)
8
+
9
+ ## [0.3]
10
+
11
+ ### Added
12
+
13
+ - `bakalari_demo.py` is now CLI application
14
+ - `Komens` now support for downloading attachment - `get_attachment`
15
+ - `send_auth_request` now supports extending EndPoints url wiht `extend` argument
16
+ - `school_list` now supports variable `town` - fetch schools in the town to limit downloading full list of schools.
17
+ - `Messages` class now have function `json` to return messages as JSON representative
18
+ - `Messages` class have `__str__` function for better handling `str(Messages)`
19
+
20
+ ### Changed
21
+
22
+ - refactor of the code for speed and better reading of the code
23
+ - `school_list` now fetching schools in concurency mode - improved speed form about 1:30 min to 20s
24
+ - `mid` variable in the `MessageContainter` is now string instead of integer.
25
+ - `async_school_list` renamed to `school_list` as all methods are async
26
+ - `MessageContainter` returns JSON bytes on `as_json()` call instead of `orjson.Fragment`
27
+ - `get_messsages()` renamed to `fetch_messages()`
28
+
29
+ ### Removed
30
+
31
+ - `username` from `Credentials` - as we do not need to store it
32
+
33
+ ## [0.2]
34
+
35
+ ### Added
36
+
37
+ - better exceptions handling and logging
38
+ - `class Komens`
39
+ - count unread messages
40
+ - get all messages
41
+ - tests and coverage
42
+
43
+ ### Changed
44
+
45
+ - `async_schools_list` moved to `Bakalari` class
46
+ - Refactor login functions
47
+ - Refactor token handling
48
+
49
+ ### Fixed
50
+
51
+ - Invalid refresh token
52
+ - Refactor send_request to better maintenance
53
+
54
+ ## [0.0.1]
55
+
56
+ ### Added
57
+
58
+ - main `class Bakalari`
59
+
60
+ - supports saving `access token` and `refresh token` localy
61
+ - automatically refreshes access token with refresh token if refresh token is not expired
62
+
63
+ - `class Schools` in `datastructures.py` lists all schools with their API points
64
+
65
+ - get_url by school name or index in list
66
+ - search school by town
67
+ - cache list of schools by saving and loading list in JSON format
68
+
69
+ [unreleased]: https://github.com/schizza/bakalari-api3/compare/v0.0.1...HEAD
70
+ [0.0.1]: https://github.com/schizza/bakalari-api3/releases/tag/v0.0.1
@@ -4,17 +4,9 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "async_bakalari_api"
7
- version = "0.2"
8
- dependencies = [
9
- "asyncio",
10
- "typing",
11
- "aiohttp",
12
- "orjson",
13
- "async_timeout",
14
- "logger",
15
- "strenum",
16
- "pytest",
17
- ]
7
+ version = "0.3"
8
+ dynamic = ["dependencies"]
9
+
18
10
 
19
11
  requires-python = ">=3.12"
20
12
  authors = [
@@ -33,9 +25,17 @@ classifiers = [
33
25
  "Programming Language :: Python"
34
26
  ]
35
27
 
28
+ [tool.setuptools.dynamic]
29
+ dependencies = { file = ["requirements.in"] }
30
+
31
+ [tool.setuptools]
32
+ platforms = ["any"]
33
+ zip-safe = false
34
+ include-package-data = true
35
+
36
36
  [project.urls]
37
37
  Homepage = "https://github.com/schizza/bakalari-api3"
38
- Documentation = "https://github.com/schizza/bakalari-api3"
38
+ Documentation = "https://async-bakalari-api.schizza.cz"
39
39
  Repository = "https://github.com/schizza/bakalari-api3"
40
40
  "Bug Tracker" = "https://github.com/schizza/bakalari-api3/issues"
41
41
  Changelog = "https://github.com/schizza/bakalari-api3/blob/master/CHANGELOG.md"
@@ -43,17 +43,18 @@ Changelog = "https://github.com/schizza/bakalari-api3/blob/master/CHANGELOG.md"
43
43
  [project.scripts]
44
44
  bakalari = "bakalari_api:main"
45
45
 
46
- [tool.setuptools]
47
- platforms = ["any"]
48
- zip-safe = false
49
- include-package-data = true
50
-
51
46
  [tool.pylint.MAIN]
52
47
  py-version = "3.12"
53
48
  ignore = [
54
49
  "tests"
55
50
  ]
56
51
 
52
+ [tool.coverage.run]
53
+ omit = [
54
+ "tests/*",
55
+ "src/bakalari_api/bakalari_demo.py"
56
+ ]
57
+
57
58
  [tool.pytest.ini_options]
58
59
  asyncio_mode = "auto"
59
60
  testpaths = [
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: async_bakalari_api
3
- Version: 0.2
3
+ Version: 0.3
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>
@@ -208,7 +208,7 @@ License:
208
208
  limitations under the License.
209
209
 
210
210
  Project-URL: Homepage, https://github.com/schizza/bakalari-api3
211
- Project-URL: Documentation, https://github.com/schizza/bakalari-api3
211
+ Project-URL: Documentation, https://async-bakalari-api.schizza.cz
212
212
  Project-URL: Repository, https://github.com/schizza/bakalari-api3
213
213
  Project-URL: Bug Tracker, https://github.com/schizza/bakalari-api3/issues
214
214
  Project-URL: Changelog, https://github.com/schizza/bakalari-api3/blob/master/CHANGELOG.md
@@ -219,57 +219,74 @@ 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: asyncio
223
- Requires-Dist: typing
224
- Requires-Dist: aiohttp
225
- Requires-Dist: orjson
226
- Requires-Dist: async_timeout
227
- Requires-Dist: logger
228
- Requires-Dist: strenum
229
- Requires-Dist: pytest
230
222
 
231
223
  [![codecov](https://codecov.io/gh/schizza/async-bakalari-api3/graph/badge.svg?token=KC2WYAOLOP)](https://codecov.io/gh/schizza/async-bakalari-api3)
232
224
 
233
- # Python async client for Bakalari API v3
225
+ # Changelog
234
226
 
235
- ### 0.0.2
227
+ All notable changes to this project will be documented in this file.
236
228
 
237
- ## Added
229
+ 🇨🇿 Full documentation (czech) on [this site](https://async-bakalari-api.schizza.cz)
238
230
 
239
- * better exceptions handling and logging
240
- * class Komens
241
- * count unread messages
242
- * get all messages
231
+ ## [0.3]
243
232
 
244
- * tests and coverage
233
+ ### Added
245
234
 
246
- ## Changed
235
+ - `bakalari_demo.py` is now CLI application
236
+ - `Komens` now support for downloading attachment - `get_attachment`
237
+ - `send_auth_request` now supports extending EndPoints url wiht `extend` argument
238
+ - `school_list` now supports variable `town` - fetch schools in the town to limit downloading full list of schools.
239
+ - `Messages` class now have function `json` to return messages as JSON representative
240
+ - `Messages` class have `__str__` function for better handling `str(Messages)`
247
241
 
248
- * async_schools_list moved to Bakalari class
249
- * Refactor login functions
250
- * Refactor token handling
242
+ ### Changed
251
243
 
252
- ## Fixed
244
+ - refactor of the code for speed and better reading of the code
245
+ - `school_list` now fetching schools in concurency mode - improved speed form about 1:30 min to 20s
246
+ - `mid` variable in the `MessageContainter` is now string instead of integer.
247
+ - `async_school_list` renamed to `school_list` as all methods are async
248
+ - `MessageContainter` returns JSON bytes on `as_json()` call instead of `orjson.Fragment`
249
+ - `get_messsages()` renamed to `fetch_messages()`
253
250
 
254
- * Invalid refresh token
255
- * Refactor send_request to better maintenance
251
+ ### Removed
256
252
 
257
- ### v0.1
253
+ - `username` from `Credentials` - as we do not need to store it
258
254
 
259
- ## Class School from `datastructure.py`
255
+ ## [0.2]
260
256
 
261
- Now supports to download list of schools with their API points.
257
+ ### Added
262
258
 
263
- * get_url by school name or index in list
264
- * search school by town
265
- * cache list of schools by saving and loading list in JSON format
259
+ - better exceptions handling and logging
260
+ - `class Komens`
261
+ - count unread messages
262
+ - get all messages
263
+ - tests and coverage
266
264
 
267
- ## Class Bakalari
265
+ ### Changed
268
266
 
269
- * first login with username and password and stores access and refresh token
270
- * automaticaly refreshes access token with refresh token if refresh token is not expired
271
- * save access and refresh token localy to be cached
267
+ - `async_schools_list` moved to `Bakalari` class
268
+ - Refactor login functions
269
+ - Refactor token handling
272
270
 
273
- ## Class Komens
271
+ ### Fixed
274
272
 
275
- * count unread messages `count_unread_messages`
273
+ - Invalid refresh token
274
+ - Refactor send_request to better maintenance
275
+
276
+ ## [0.0.1]
277
+
278
+ ### Added
279
+
280
+ - main `class Bakalari`
281
+
282
+ - supports saving `access token` and `refresh token` localy
283
+ - automatically refreshes access token with refresh token if refresh token is not expired
284
+
285
+ - `class Schools` in `datastructures.py` lists all schools with their API points
286
+
287
+ - get_url by school name or index in list
288
+ - search school by town
289
+ - cache list of schools by saving and loading list in JSON format
290
+
291
+ [unreleased]: https://github.com/schizza/bakalari-api3/compare/v0.0.1...HEAD
292
+ [0.0.1]: https://github.com/schizza/bakalari-api3/releases/tag/v0.0.1
@@ -7,7 +7,6 @@ src/async_bakalari_api.egg-info/SOURCES.txt
7
7
  src/async_bakalari_api.egg-info/dependency_links.txt
8
8
  src/async_bakalari_api.egg-info/entry_points.txt
9
9
  src/async_bakalari_api.egg-info/not-zip-safe
10
- src/async_bakalari_api.egg-info/requires.txt
11
10
  src/async_bakalari_api.egg-info/top_level.txt
12
11
  src/bakalari_api/__init__.py
13
12
  src/bakalari_api/__main__.py
@@ -18,4 +17,8 @@ src/bakalari_api/datastructure.py
18
17
  src/bakalari_api/exceptions.py
19
18
  src/bakalari_api/first_login.py
20
19
  src/bakalari_api/komens.py
21
- src/bakalari_api/logger_api.py
20
+ src/bakalari_api/logger_api.py
21
+ tests/test_bakalari.py
22
+ tests/test_const.py
23
+ tests/test_datastructure.py
24
+ tests/test_komens.py
@@ -23,7 +23,6 @@ log = api_logger("Bakalari API", loglevel=logging.ERROR).get()
23
23
  class Bakalari:
24
24
  """Root class of Bakalari."""
25
25
 
26
- session: aiohttp.ClientSession | None = None
27
26
  response: None
28
27
  response_json: None
29
28
 
@@ -51,14 +50,32 @@ class Bakalari:
51
50
  self.new_token = False
52
51
  self.auto_cache_credentials = auto_cache_credentials
53
52
  self.cache_filename = cache_filename
53
+ self.session = aiohttp.ClientSession()
54
54
 
55
55
  if self.auto_cache_credentials and not self.cache_filename:
56
56
  raise Ex.CacheError("Auto-cache is enabled, but no filename is provided!")
57
57
 
58
- async def send_auth_request(self, request_endpoint: EndPoint, **kwargs):
58
+ def __del__(self):
59
+ """Destructor."""
60
+ # Close connection when this object is destroyed
61
+ try:
62
+ loop = asyncio.get_event_loop()
63
+ if loop.is_running():
64
+ return loop.create_task(self.session.close())
65
+ loop.run_until_complete(self.session.close())
66
+ finally:
67
+ pass
68
+
69
+ async def send_auth_request(
70
+ self, request_endpoint: EndPoint, extend: str | None = None, **kwargs
71
+ ):
59
72
  """Send authorized request with access token or refresh token."""
60
73
 
61
74
  request = self.get_request_url(request_endpoint)
75
+
76
+ if extend:
77
+ request += extend
78
+
62
79
  method = hdrs.METH_POST if "post" in request_endpoint.method else hdrs.METH_GET
63
80
 
64
81
  access_token_invalid = False
@@ -92,7 +109,6 @@ class Bakalari:
92
109
  return result
93
110
 
94
111
  if access_token_invalid and self.refresh_access_token:
95
- log.debug("Trying refresh token ...")
96
112
  try:
97
113
  await self.refresh_access_token()
98
114
  except Ex.RefreshTokenExpired as ex:
@@ -160,23 +176,34 @@ class Bakalari:
160
176
 
161
177
  """
162
178
 
163
- if not self.session or self.session.closed:
164
- self.session = aiohttp.ClientSession()
179
+ filedata = None
180
+ filename = None
181
+
182
+ if method == hdrs.METH_GET:
183
+ session = self.session.get
184
+ else:
185
+ session = self.session.post
165
186
 
166
187
  log.debug("Requesting URL %s, kwargs: %s", url, kwargs)
167
188
  try:
168
189
  async with asyncio.timeout(REQUEST_TIMEOUT):
169
- async with self.session:
170
- if method == hdrs.METH_GET:
171
- response = await self.session.get(
172
- url, ssl=True, headers=headers, **kwargs
190
+
191
+ async with session(
192
+ url, ssl=True, headers=headers, **kwargs
193
+ ) as response:
194
+
195
+ if (
196
+ response.headers.get(aiohttp.hdrs.CONTENT_TYPE)
197
+ == "application/octet-stream"
198
+ ):
199
+ filedata = await response.read()
200
+ filename = response.headers[aiohttp.hdrs.CONTENT_DISPOSITION]
201
+ filename = parse.unquote(
202
+ filename[filename.rindex("filename*=") + 17 :]
173
203
  )
174
204
  else:
175
- response = await self.session.post(
176
- url, ssl=True, headers=headers, **kwargs
177
- )
178
- response_json = await response.json()
179
- log.debug(f"Response: {response}")
205
+ response_json = await response.json()
206
+ log.debug(f"Response: {response_json}")
180
207
 
181
208
  except TimeoutError as err:
182
209
  raise Ex.TimeoutException(
@@ -216,29 +243,37 @@ class Bakalari:
216
243
  raise Ex.BadRequestException(
217
244
  f"{url} with message: {response_json}"
218
245
  )
246
+ case 404:
247
+ raise Ex.BadRequestException(f"Not found! ({url})")
219
248
  case 200:
220
- return response_json
249
+ return [filename, filedata] if filedata else response_json
221
250
  case _:
222
251
  raise Ex.BadRequestException(f"{url} with message: {response_json}")
223
252
 
224
- async def async_schools_list(self) -> Schools:
253
+ async def schools_list(self, town: str | None = None) -> Schools:
225
254
  """Return list of schools with their API points."""
226
255
 
227
256
  _schools_list = Schools()
228
257
  headers = {"Accept": "application/json"}
229
258
 
230
- log.debug("Gathering list of towns ...")
231
- try:
232
- towns_json = await self.send_unauth_request(EndPoint.SCHOOL_LIST, headers)
233
- except Exception as exc:
234
- log.error(f"Error while gathering schools endpoints. {exc}")
235
- return None
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}"}]
236
270
 
237
271
  schools: list = []
272
+ tasks = []
238
273
 
239
- for town in towns_json:
240
- town_name = str(town["name"])
241
- if town_name == "":
274
+ for _town in towns_json:
275
+ town_name = str(_town["name"])
276
+ if town_name == "" or None:
242
277
  continue
243
278
  if "." in town_name:
244
279
  town_name = town_name[: town_name.find(".")]
@@ -247,14 +282,20 @@ class Bakalari:
247
282
 
248
283
  endpoint = f"{EndPoint.SCHOOL_LIST.endpoint}/{parse.quote(town_name)}"
249
284
 
250
- response_town = await self._send_request(endpoint, hdrs.METH_GET, headers)
285
+ task = asyncio.create_task(
286
+ self._send_request(endpoint, hdrs.METH_GET, headers), name=town_name
287
+ )
288
+ tasks.append(task)
289
+
290
+ responses = await asyncio.gather(*tasks)
291
+ for response_town in responses:
251
292
 
252
293
  schools: dict = response_town
253
294
  for _schools in schools.get("schools"):
254
295
  _schools_list.append_school(
255
296
  name=_schools.get("name"),
256
297
  api_point=_schools.get("schoolUrl"),
257
- town=town_name,
298
+ town=response_town.get("name"),
258
299
  )
259
300
 
260
301
  return _schools_list
@@ -265,13 +306,21 @@ class Bakalari:
265
306
  Create access and refresh tokens.
266
307
  """
267
308
 
268
- login_url = f"client_id=ANDR&grant_type=password&username={username}&password={password}"
309
+ login_params = parse.urlencode(
310
+ {
311
+ "client_id": "ANDR",
312
+ "grant_type": "password",
313
+ "username": username,
314
+ "password": password,
315
+ }
316
+ )
317
+
269
318
  headers = {"Content-Type": "application/x-www-form-urlencoded"}
270
319
 
271
320
  try:
272
- log.debug("Trying to login with username and password ...")
321
+ log.debug(f"Trying to login with username: {username}")
273
322
  _credentials = await self.send_unauth_request(
274
- EndPoint.LOGIN, data=login_url, headers=headers
323
+ EndPoint.LOGIN, data=login_params, headers=headers
275
324
  )
276
325
  except Ex.InvalidLogin as ex:
277
326
  log.error("Invalid username / password provided.")
@@ -279,6 +328,8 @@ class Bakalari:
279
328
  _credentials.update({"username": username})
280
329
  self.credentials = Credentials.create(_credentials)
281
330
 
331
+ log.info(f"Successfully logged in with username: {username}")
332
+
282
333
  if self.auto_cache_credentials:
283
334
  self.save_credentials()
284
335
  return self.credentials
@@ -288,7 +339,13 @@ class Bakalari:
288
339
 
289
340
  returns new Credentials if success, else RefreshTokenExpired exception
290
341
  """
291
- login_body = f"client_id=ANDR&grant_type=refresh_token&refresh_token={self.credentials.refresh_token}"
342
+ login_body = parse.urlencode(
343
+ {
344
+ "client_id": "ANDR",
345
+ "grant_type": "refresh_token",
346
+ "refresh_token": self.credentials.refresh_token,
347
+ }
348
+ )
292
349
  headers = {"Content-Type": "application/x-www-form-urlencoded"}
293
350
 
294
351
  try:
@@ -319,6 +376,7 @@ class Bakalari:
319
376
  str: full url of endpoint
320
377
 
321
378
  """
379
+
322
380
  request = (
323
381
  request_endpoint.endpoint
324
382
  if request_endpoint.endpoint.lower().startswith(("http", "https"))
@@ -336,13 +394,12 @@ class Bakalari:
336
394
  If auto_save_credentials are enabled, parameters could be ommited.
337
395
  """
338
396
 
339
- if not filename and self.auto_cache_credentials:
340
- filename = self.cache_filename
397
+ filename = filename or self.cache_filename
341
398
  try:
342
399
  with open(filename, "wb") as file:
343
400
  file.write(orjson.dumps(self.credentials, option=orjson.OPT_INDENT_2))
344
- file.close()
345
- except OSError:
401
+ except OSError as err:
402
+ log.error(f"Error while saving credentials to file {filename}. {str(err)}")
346
403
  return False
347
404
 
348
405
  return True
@@ -353,11 +410,12 @@ class Bakalari:
353
410
  try:
354
411
  with open(filename, "rb") as file:
355
412
  data = orjson.loads(file.read())
356
- file.close()
357
- except OSError:
413
+ except (OSError, orjson.JSONDecodeError):
414
+ log.error(f"Error while loading credentials from file {filename}")
358
415
  return False
359
416
 
360
417
  self.credentials = Credentials.create_from_json(data)
418
+
361
419
  return self.credentials
362
420
 
363
421
  async def __aenter__(self) -> Self: