42api 0.1.3__tar.gz → 0.1.5__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 (101) hide show
  1. 42api-0.1.5/.github/dependabot.yml +26 -0
  2. {42api-0.1.3 → 42api-0.1.5}/.github/workflows/ci.yml +6 -5
  3. {42api-0.1.3 → 42api-0.1.5}/.github/workflows/publish.yml +4 -3
  4. {42api-0.1.3 → 42api-0.1.5}/.gitignore +1 -1
  5. {42api-0.1.3 → 42api-0.1.5}/PKG-INFO +2 -3
  6. {42api-0.1.3 → 42api-0.1.5}/pyproject.toml +3 -4
  7. {42api-0.1.3 → 42api-0.1.5}/src/intra42/__init__.py +8 -1
  8. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_async/client.py +78 -9
  9. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_async/query.py +7 -3
  10. 42api-0.1.5/src/intra42/_async/resources/accreditations.py +26 -0
  11. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_async/resources/base.py +16 -2
  12. 42api-0.1.5/src/intra42/_async/resources/campuses.py +37 -0
  13. 42api-0.1.5/src/intra42/_async/resources/cursus.py +37 -0
  14. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_async/resources/exams.py +3 -2
  15. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_async/resources/locations.py +3 -2
  16. 42api-0.1.5/src/intra42/_async/resources/projects.py +26 -0
  17. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_async/resources/projects_users.py +3 -2
  18. 42api-0.1.5/src/intra42/_async/resources/users.py +43 -0
  19. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_auth.py +6 -0
  20. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_config.py +3 -0
  21. 42api-0.1.5/src/intra42/_paths.py +18 -0
  22. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_sync/client.py +78 -9
  23. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_sync/query.py +7 -3
  24. 42api-0.1.5/src/intra42/_sync/resources/accreditations.py +32 -0
  25. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_sync/resources/base.py +16 -2
  26. 42api-0.1.5/src/intra42/_sync/resources/campuses.py +43 -0
  27. 42api-0.1.5/src/intra42/_sync/resources/cursus.py +43 -0
  28. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_sync/resources/exams.py +3 -2
  29. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_sync/resources/locations.py +3 -2
  30. 42api-0.1.5/src/intra42/_sync/resources/projects.py +32 -0
  31. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_sync/resources/projects_users.py +3 -2
  32. 42api-0.1.5/src/intra42/_sync/resources/users.py +49 -0
  33. 42api-0.1.5/tests/integration/test_nested_methods.py +109 -0
  34. 42api-0.1.5/tests/integration/test_origin_check_and_auth_retry.py +180 -0
  35. {42api-0.1.3 → 42api-0.1.5}/tests/integration/test_pagination_walk.py +28 -0
  36. 42api-0.1.5/tests/integration/test_path_encoding.py +75 -0
  37. 42api-0.1.5/tests/integration/test_transient_retries.py +193 -0
  38. 42api-0.1.5/tests/live/conftest.py +55 -0
  39. 42api-0.1.5/tests/live/test_live_api.py +63 -0
  40. 42api-0.1.5/tests/unit/test_nested_typing.py +59 -0
  41. 42api-0.1.5/tests/unit/test_paths.py +25 -0
  42. 42api-0.1.5/uv.lock +846 -0
  43. 42api-0.1.3/src/intra42/_async/resources/accreditations.py +0 -16
  44. 42api-0.1.3/src/intra42/_async/resources/campuses.py +0 -23
  45. 42api-0.1.3/src/intra42/_async/resources/cursus.py +0 -23
  46. 42api-0.1.3/src/intra42/_async/resources/projects.py +0 -19
  47. 42api-0.1.3/src/intra42/_async/resources/users.py +0 -27
  48. 42api-0.1.3/src/intra42/_sync/resources/accreditations.py +0 -22
  49. 42api-0.1.3/src/intra42/_sync/resources/campuses.py +0 -29
  50. 42api-0.1.3/src/intra42/_sync/resources/cursus.py +0 -29
  51. 42api-0.1.3/src/intra42/_sync/resources/projects.py +0 -25
  52. 42api-0.1.3/src/intra42/_sync/resources/users.py +0 -33
  53. 42api-0.1.3/uv.lock +0 -935
  54. {42api-0.1.3 → 42api-0.1.5}/.pre-commit-config.yaml +0 -0
  55. {42api-0.1.3 → 42api-0.1.5}/LICENSE +0 -0
  56. {42api-0.1.3 → 42api-0.1.5}/README.md +0 -0
  57. {42api-0.1.3 → 42api-0.1.5}/scripts/unasync_generate.py +0 -0
  58. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_async/__init__.py +0 -0
  59. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_async/resources/__init__.py +0 -0
  60. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_async/resources/campus_users.py +0 -0
  61. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_async/resources/events.py +0 -0
  62. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_pagination.py +0 -0
  63. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_query_params.py +0 -0
  64. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_rate_limit.py +0 -0
  65. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_sync/__init__.py +0 -0
  66. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_sync/resources/__init__.py +0 -0
  67. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_sync/resources/campus_users.py +0 -0
  68. {42api-0.1.3 → 42api-0.1.5}/src/intra42/_sync/resources/events.py +0 -0
  69. {42api-0.1.3 → 42api-0.1.5}/src/intra42/exceptions.py +0 -0
  70. {42api-0.1.3 → 42api-0.1.5}/src/intra42/models/__init__.py +0 -0
  71. {42api-0.1.3 → 42api-0.1.5}/src/intra42/models/accreditation.py +0 -0
  72. {42api-0.1.3 → 42api-0.1.5}/src/intra42/models/base.py +0 -0
  73. {42api-0.1.3 → 42api-0.1.5}/src/intra42/models/campus.py +0 -0
  74. {42api-0.1.3 → 42api-0.1.5}/src/intra42/models/campus_user.py +0 -0
  75. {42api-0.1.3 → 42api-0.1.5}/src/intra42/models/cursus.py +0 -0
  76. {42api-0.1.3 → 42api-0.1.5}/src/intra42/models/event.py +0 -0
  77. {42api-0.1.3 → 42api-0.1.5}/src/intra42/models/exam.py +0 -0
  78. {42api-0.1.3 → 42api-0.1.5}/src/intra42/models/location.py +0 -0
  79. {42api-0.1.3 → 42api-0.1.5}/src/intra42/models/project.py +0 -0
  80. {42api-0.1.3 → 42api-0.1.5}/src/intra42/models/project_user.py +0 -0
  81. {42api-0.1.3 → 42api-0.1.5}/src/intra42/models/user.py +0 -0
  82. {42api-0.1.3 → 42api-0.1.5}/src/intra42/py.typed +0 -0
  83. {42api-0.1.3 → 42api-0.1.5}/tests/conftest.py +0 -0
  84. {42api-0.1.3 → 42api-0.1.5}/tests/integration/resources/test_resources_accreditations.py +0 -0
  85. {42api-0.1.3 → 42api-0.1.5}/tests/integration/resources/test_resources_campus_users.py +0 -0
  86. {42api-0.1.3 → 42api-0.1.5}/tests/integration/resources/test_resources_campuses.py +0 -0
  87. {42api-0.1.3 → 42api-0.1.5}/tests/integration/resources/test_resources_cursus.py +0 -0
  88. {42api-0.1.3 → 42api-0.1.5}/tests/integration/resources/test_resources_events.py +0 -0
  89. {42api-0.1.3 → 42api-0.1.5}/tests/integration/resources/test_resources_exams.py +0 -0
  90. {42api-0.1.3 → 42api-0.1.5}/tests/integration/resources/test_resources_locations.py +0 -0
  91. {42api-0.1.3 → 42api-0.1.5}/tests/integration/resources/test_resources_projects.py +0 -0
  92. {42api-0.1.3 → 42api-0.1.5}/tests/integration/resources/test_resources_projects_users.py +0 -0
  93. {42api-0.1.3 → 42api-0.1.5}/tests/integration/test_client_integration.py +0 -0
  94. {42api-0.1.3 → 42api-0.1.5}/tests/integration/test_nested_access.py +0 -0
  95. {42api-0.1.3 → 42api-0.1.5}/tests/unit/test_auth.py +0 -0
  96. {42api-0.1.3 → 42api-0.1.5}/tests/unit/test_models_campus.py +0 -0
  97. {42api-0.1.3 → 42api-0.1.5}/tests/unit/test_models_user.py +0 -0
  98. {42api-0.1.3 → 42api-0.1.5}/tests/unit/test_pagination.py +0 -0
  99. {42api-0.1.3 → 42api-0.1.5}/tests/unit/test_public_api.py +0 -0
  100. {42api-0.1.3 → 42api-0.1.5}/tests/unit/test_query_builder.py +0 -0
  101. {42api-0.1.3 → 42api-0.1.5}/tests/unit/test_rate_limit.py +0 -0
@@ -0,0 +1,26 @@
1
+ version: 2
2
+
3
+ updates:
4
+ # Python dependencies, resolved via uv.lock.
5
+ - package-ecosystem: "uv"
6
+ directory: "/"
7
+ schedule:
8
+ interval: "weekly"
9
+ open-pull-requests-limit: 10
10
+ labels:
11
+ - "dependencies"
12
+ commit-message:
13
+ prefix: "deps"
14
+
15
+ # Keep the CI/publish workflows' pinned actions
16
+ # patched too, action versions get security
17
+ # advisories same as any other dependency.
18
+ - package-ecosystem: "github-actions"
19
+ directory: "/"
20
+ schedule:
21
+ interval: "weekly"
22
+ labels:
23
+ - "dependencies"
24
+ - "ci"
25
+ commit-message:
26
+ prefix: "ci"
@@ -2,7 +2,7 @@ name: CI
2
2
 
3
3
  on:
4
4
  push:
5
- branches: [master]
5
+ branches: [master, dev]
6
6
  pull_request:
7
7
 
8
8
  jobs:
@@ -10,14 +10,15 @@ jobs:
10
10
  runs-on: ubuntu-latest
11
11
  strategy:
12
12
  matrix:
13
- python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
13
+ python-version: ["3.11", "3.12", "3.13", "3.14"]
14
14
  steps:
15
- - uses: actions/checkout@v4
15
+ - uses: actions/checkout@v7
16
16
 
17
17
  - name: Install uv
18
- uses: astral-sh/setup-uv@v3
18
+ uses: astral-sh/setup-uv@v7
19
19
  with:
20
- version: "latest"
20
+ # Pinned for reproducible builds, keep in sync with publish.yml.
21
+ version: "0.11.16"
21
22
 
22
23
  - name: Set up Python ${{ matrix.python-version }}
23
24
  run: uv python install ${{ matrix.python-version }}
@@ -16,12 +16,13 @@ jobs:
16
16
  name: pypi
17
17
  url: https://pypi.org/project/42api/
18
18
  steps:
19
- - uses: actions/checkout@v4
19
+ - uses: actions/checkout@v7
20
20
 
21
21
  - name: Install uv
22
- uses: astral-sh/setup-uv@v3
22
+ uses: astral-sh/setup-uv@v7
23
23
  with:
24
- version: "latest"
24
+ # Pinned for reproducible builds, keep in sync with ci.yml.
25
+ version: "0.11.16"
25
26
 
26
27
  - name: Set up Python
27
28
  run: uv python install 3.12
@@ -187,7 +187,7 @@ cython_debug/
187
187
  # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
188
188
  # and can be added to the global gitignore or merged into this file. For a more nuclear
189
189
  # option (not recommended) you can uncomment the following to ignore the entire idea folder.
190
- # .idea/
190
+ .idea/
191
191
 
192
192
  # Abstra
193
193
  # Abstra is an AI-powered process automation framework.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: 42api
3
- Version: 0.1.3
3
+ Version: 0.1.5
4
4
  Summary: Object-oriented Python client for the 42 School API (api.intra.42.fr)
5
5
  Project-URL: Homepage, https://github.com/Shadowaker/42api
6
6
  Author-email: Dan <danyridolfo98@gmail.com>
@@ -13,13 +13,12 @@ Classifier: Intended Audience :: Developers
13
13
  Classifier: License :: OSI Approved :: MIT License
14
14
  Classifier: Operating System :: OS Independent
15
15
  Classifier: Programming Language :: Python :: 3
16
- Classifier: Programming Language :: Python :: 3.10
17
16
  Classifier: Programming Language :: Python :: 3.11
18
17
  Classifier: Programming Language :: Python :: 3.12
19
18
  Classifier: Programming Language :: Python :: 3.13
20
19
  Classifier: Programming Language :: Python :: 3.14
21
20
  Classifier: Typing :: Typed
22
- Requires-Python: >=3.10
21
+ Requires-Python: >=3.11
23
22
  Requires-Dist: httpx>=0.27
24
23
  Requires-Dist: pydantic>=2.0
25
24
  Description-Content-Type: text/markdown
@@ -1,10 +1,10 @@
1
1
  [project]
2
2
  name = "42api"
3
- version = "0.1.3"
3
+ version = "0.1.5"
4
4
  description = "Object-oriented Python client for the 42 School API (api.intra.42.fr)"
5
5
  readme = "README.md"
6
6
  license = { text = "MIT" }
7
- requires-python = ">=3.10"
7
+ requires-python = ">=3.11"
8
8
  authors = [{ name = "Dan", email = "danyridolfo98@gmail.com" }]
9
9
  dependencies = ["httpx>=0.27", "pydantic>=2.0"]
10
10
 
@@ -14,7 +14,6 @@ classifiers = [
14
14
  "License :: OSI Approved :: MIT License",
15
15
  "Operating System :: OS Independent",
16
16
  "Programming Language :: Python :: 3",
17
- "Programming Language :: Python :: 3.10",
18
17
  "Programming Language :: Python :: 3.11",
19
18
  "Programming Language :: Python :: 3.12",
20
19
  "Programming Language :: Python :: 3.13",
@@ -57,7 +56,7 @@ target-version = "py310"
57
56
  select = ["E", "F", "I", "UP", "B"]
58
57
 
59
58
  [tool.mypy]
60
- python_version = "3.10"
59
+ python_version = "3.11"
61
60
  packages = ["intra42"]
62
61
  mypy_path = "src"
63
62
  disallow_untyped_defs = true
@@ -12,6 +12,8 @@ An async client with the same interface is available as ``AsyncClient``.
12
12
 
13
13
  from __future__ import annotations
14
14
 
15
+ from importlib.metadata import PackageNotFoundError, version
16
+
15
17
  from ._async.client import AsyncClient
16
18
  from ._config import ClientConfig
17
19
  from ._sync.client import Client
@@ -60,4 +62,9 @@ __all__ = [
60
62
  "NetworkError",
61
63
  ]
62
64
 
63
- __version__ = "0.1.3"
65
+ # Single source of truth is pyproject.toml; read it from the installed
66
+ # distribution metadata rather than hardcoding a copy that drifts.
67
+ try:
68
+ __version__ = version("42api")
69
+ except PackageNotFoundError: # pragma: no cover - running from an uninstalled source tree
70
+ __version__ = "0.0.0+unknown"
@@ -4,14 +4,16 @@ implementation of the request logic here.
4
4
 
5
5
  from __future__ import annotations
6
6
 
7
+ import random
7
8
  from typing import Any
9
+ from urllib.parse import urlsplit
8
10
 
9
11
  import httpx
10
12
 
11
13
  from .._auth import TokenManager
12
14
  from .._config import DEFAULT_BASE_URL, ClientConfig
13
15
  from .._rate_limit import RateLimiter
14
- from ..exceptions import NetworkError, raise_for_status
16
+ from ..exceptions import FortyTwoAPIError, NetworkError, raise_for_status
15
17
  from .resources.accreditations import AsyncAccreditationsResource
16
18
  from .resources.campus_users import AsyncCampusUsersResource
17
19
  from .resources.campuses import AsyncCampusesResource
@@ -23,6 +25,21 @@ from .resources.projects import AsyncProjectsResource
23
25
  from .resources.projects_users import AsyncProjectUsersResource
24
26
  from .resources.users import AsyncUsersResource
25
27
 
28
+ # Gateway/availability errors that are usually transient. 500 is left out on
29
+ # purpose: it typically signals a deterministic server-side bug.
30
+ _RETRYABLE_STATUSES = frozenset({502, 503, 504})
31
+ # Methods safe to resend after the server may already have processed them.
32
+ _IDEMPOTENT_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
33
+ # Failures raised before the request reached the server: safe to retry for
34
+ # any method, since nothing was sent.
35
+ _NOT_SENT_ERRORS = (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout)
36
+ _MAX_BACKOFF = 8.0
37
+
38
+
39
+ def _backoff_delay(base: float, retry: int) -> float:
40
+ """Full-jitter exponential backoff: ``uniform(0, min(cap, base * 2**retry))``."""
41
+ return random.uniform(0.0, min(_MAX_BACKOFF, base * 2**retry))
42
+
26
43
 
27
44
  def _parse_retry_after(value: str | None) -> float:
28
45
  """Parse a ``Retry-After`` header value as seconds.
@@ -77,7 +94,18 @@ class AsyncClient:
77
94
  return self._config.base_url
78
95
 
79
96
  def _build_url(self, path: str) -> str:
97
+ """
98
+ Resolve ``path`` against ``base_url``.
99
+
100
+ Absolute URLs are accepted only when their scheme and host match ``base_url``:
101
+ every request carries the Bearer token, so following a URL to any other
102
+ origin would leak it.
103
+ """
80
104
  if path.startswith("http://") or path.startswith("https://"):
105
+ target = urlsplit(path)
106
+ base = urlsplit(self._config.base_url)
107
+ if (target.scheme, target.netloc.lower()) != (base.scheme, base.netloc.lower()):
108
+ raise FortyTwoAPIError("URL does not match base_url")
81
109
  return path
82
110
  return f"{self._config.base_url}{path}"
83
111
 
@@ -94,11 +122,30 @@ class AsyncClient:
94
122
  Retries on 429 up to ``max_retries`` times, honoring the response's
95
123
  ``Retry-After`` header via the shared rate limiter's cooldown gate,
96
124
  before raising :class:`intra42.exceptions.RateLimitError`.
125
+
126
+ Transient failures (502/503/504 and network errors) are retried with
127
+ full-jitter exponential backoff, honoring ``Retry-After`` when the
128
+ server sends one. Only idempotent methods (GET/HEAD/OPTIONS) are
129
+ retried, except for connection failures where the request was never
130
+ sent. 429s and transient failures share the ``max_retries`` budget;
131
+ once it's spent, :class:`intra42.exceptions.ServerError` or
132
+ :class:`intra42.exceptions.NetworkError` is raised.
133
+
134
+ Backoff waits go through the rate limiter's shared cooldown gate, so
135
+ they also pause other in-flight requests on this client — deliberate,
136
+ since a struggling server or network affects them all.
137
+
138
+ On a 401 the cached token is discarded and the request is retried
139
+ once with a freshly fetched token (it may have been revoked or
140
+ expired server-side early); a second 401 raises
141
+ :class:`intra42.exceptions.AuthenticationError`.
97
142
  """
98
143
  url = self._build_url(path)
99
- response: httpx.Response | None = None
144
+ idempotent = method.upper() in _IDEMPOTENT_METHODS
145
+ retries = 0
146
+ auth_retried = False
100
147
 
101
- for attempt in range(self._config.max_retries + 1):
148
+ while True:
102
149
  token = await self._token_manager.aensure_token(self._http)
103
150
  await self._rate_limiter.aacquire()
104
151
  try:
@@ -110,22 +157,44 @@ class AsyncClient:
110
157
  headers={"Authorization": f"Bearer {token}"},
111
158
  )
112
159
  except httpx.TransportError as exc:
160
+ retryable = idempotent or isinstance(exc, _NOT_SENT_ERRORS)
161
+ if retryable and retries < self._config.max_retries:
162
+ self._rate_limiter.notify_retry_after(
163
+ _backoff_delay(self._config.retry_backoff, retries)
164
+ )
165
+ retries += 1
166
+ continue
113
167
  raise NetworkError(f"Request to {url} failed: {exc}") from exc
114
168
 
115
- if response.status_code == 429:
169
+ status = response.status_code
170
+
171
+ if status == 401 and not auth_retried:
172
+ auth_retried = True
173
+ self._token_manager.invalidate(token)
174
+ continue
175
+
176
+ if status == 429:
116
177
  self._rate_limiter.notify_retry_after(
117
178
  _parse_retry_after(response.headers.get("Retry-After"))
118
179
  )
119
- if attempt < self._config.max_retries:
180
+ if retries < self._config.max_retries:
181
+ retries += 1
120
182
  continue
183
+ elif (
184
+ status in _RETRYABLE_STATUSES and idempotent and retries < self._config.max_retries
185
+ ):
186
+ retry_after = response.headers.get("Retry-After")
187
+ self._rate_limiter.notify_retry_after(
188
+ _parse_retry_after(retry_after)
189
+ if retry_after is not None
190
+ else _backoff_delay(self._config.retry_backoff, retries)
191
+ )
192
+ retries += 1
193
+ continue
121
194
 
122
195
  raise_for_status(response)
123
196
  return response
124
197
 
125
- assert response is not None # loop always runs at least once
126
- raise_for_status(response)
127
- return response # pragma: no cover - raise_for_status always raises on a 429
128
-
129
198
  async def aclose(self) -> None:
130
199
  await self._http.aclose()
131
200
 
@@ -71,10 +71,13 @@ class AsyncQuerySet(Generic[ModelT]):
71
71
  return clone
72
72
 
73
73
  def _initial_params(self) -> dict[str, str]:
74
+ page_size = self._page_size
75
+ if page_size is None:
76
+ page_size = self._client._config.default_page_size
74
77
  return build_query_params(
75
78
  filters=self._filters,
76
79
  sort=self._sort_fields,
77
- page_size=self._page_size,
80
+ page_size=page_size,
78
81
  ranges=self._ranges,
79
82
  )
80
83
 
@@ -108,7 +111,8 @@ class AsyncQuerySet(Generic[ModelT]):
108
111
  split = urlsplit(next_url)
109
112
  url = f"{split.scheme}://{split.netloc}{split.path}" if split.scheme else split.path
110
113
  next_query = dict(parse_qsl(split.query))
111
- page_number = next_query.pop("page[number]", None) or next_query.pop("page", None)
114
+ bare_page = next_query.pop("page", None)
115
+ page_number = next_query.pop("page[number]", None) or bare_page
112
116
  params = {**next_query, **base_params}
113
117
  if page_number is not None:
114
118
  params["page[number]"] = page_number
@@ -117,6 +121,6 @@ class AsyncQuerySet(Generic[ModelT]):
117
121
  return [item async for item in self]
118
122
 
119
123
  async def first(self) -> ModelT | None:
120
- async for item in self:
124
+ async for item in self.page_size(1):
121
125
  return item
122
126
  return None
@@ -0,0 +1,26 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from ...models.accreditation import Accreditation
6
+ from .base import AsyncResource
7
+
8
+ if TYPE_CHECKING:
9
+ from ...models.user import User
10
+ from ..query import AsyncQuerySet
11
+
12
+
13
+ class AsyncAccreditationsResource(AsyncResource[Accreditation]):
14
+ path = "/accreditations"
15
+ model = Accreditation
16
+
17
+ def users(self, accreditation: int | Accreditation) -> AsyncQuerySet[User]:
18
+ """Users holding an accreditation (``GET /accreditations/{id}/users``).
19
+
20
+ Referenced in the users apidoc page. ``Accreditation.users``
21
+ delegates here.
22
+ """
23
+ return self._client.users._queryset(self._scoped_path(accreditation, "users"))
24
+
25
+ def _bind_relations(self, instance: Accreditation) -> None:
26
+ instance._bind_relation("users", lambda: self.users(instance))
@@ -16,6 +16,7 @@ from __future__ import annotations
16
16
  from collections.abc import AsyncIterator
17
17
  from typing import TYPE_CHECKING, Any, ClassVar, Generic, TypeVar, cast
18
18
 
19
+ from ..._paths import path_segment
19
20
  from ...models.base import FortyTwoModel
20
21
  from ..query import AsyncQuerySet
21
22
 
@@ -32,6 +33,15 @@ class AsyncResource(Generic[ModelT]):
32
33
  def __init__(self, client: AsyncClient) -> None:
33
34
  self._client = client
34
35
 
36
+ def _scoped_path(self, parent: int | str | FortyTwoModel, sub_path: str) -> str:
37
+ """Build ``{path}/{parent_id}/{sub_path}`` for a nested-resource method.
38
+
39
+ ``parent`` may be an id/login or an already-fetched instance,
40
+ so callers can skip fetching the parent first.
41
+ """
42
+ parent_id = parent if isinstance(parent, (int, str)) else cast(Any, parent).id
43
+ return f"{self.path}/{path_segment(parent_id)}/{sub_path}"
44
+
35
45
  def _bind_relations(self, instance: ModelT) -> None:
36
46
  """Attach nested-resource accessors to a freshly parsed instance.
37
47
 
@@ -41,8 +51,12 @@ class AsyncResource(Generic[ModelT]):
41
51
  return
42
52
 
43
53
  async def get(self, id: int | str) -> ModelT:
44
- """Fetch a single resource by id: ``GET {path}/{id}``."""
45
- response = await self._client.request("GET", f"{self.path}/{id}")
54
+ """Fetch a single resource by id: ``GET {path}/{id}``.
55
+
56
+ ``id`` is percent-encoded as one path segment; raises ``ValueError``
57
+ for an empty, ``"."`` or ``".."`` id.
58
+ """
59
+ response = await self._client.request("GET", f"{self.path}/{path_segment(id)}")
46
60
  instance = cast(ModelT, self.model.model_validate(response.json()))
47
61
  self._bind_relations(instance)
48
62
  return instance
@@ -0,0 +1,37 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from ...models.campus import Campus
6
+ from .base import AsyncResource
7
+
8
+ if TYPE_CHECKING:
9
+ from ...models.event import Event
10
+ from ...models.location import Location
11
+ from ...models.user import User
12
+ from ..query import AsyncQuerySet
13
+
14
+
15
+ class AsyncCampusesResource(AsyncResource[Campus]):
16
+ path = "/campus"
17
+ model = Campus
18
+
19
+ # Exactly-typed nested accessors. `campus` may be an id or a fetched
20
+ # Campus; the matching `Campus.<name>` properties delegate here.
21
+
22
+ def users(self, campus: int | Campus) -> AsyncQuerySet[User]:
23
+ """Users of a campus (``GET /campus/{id}/users``)."""
24
+ return self._client.users._queryset(self._scoped_path(campus, "users"))
25
+
26
+ def events(self, campus: int | Campus) -> AsyncQuerySet[Event]:
27
+ """Events at a campus (``GET /campus/{id}/events``)."""
28
+ return self._client.events._queryset(self._scoped_path(campus, "events"))
29
+
30
+ def locations(self, campus: int | Campus) -> AsyncQuerySet[Location]:
31
+ """Login sessions at a campus (``GET /campus/{id}/locations``)."""
32
+ return self._client.locations._queryset(self._scoped_path(campus, "locations"))
33
+
34
+ def _bind_relations(self, instance: Campus) -> None:
35
+ instance._bind_relation("users", lambda: self.users(instance))
36
+ instance._bind_relation("events", lambda: self.events(instance))
37
+ instance._bind_relation("locations", lambda: self.locations(instance))
@@ -0,0 +1,37 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from ...models.cursus import Cursus
6
+ from .base import AsyncResource
7
+
8
+ if TYPE_CHECKING:
9
+ from ...models.event import Event
10
+ from ...models.project import Project
11
+ from ...models.user import User
12
+ from ..query import AsyncQuerySet
13
+
14
+
15
+ class AsyncCursusResource(AsyncResource[Cursus]):
16
+ path = "/cursus"
17
+ model = Cursus
18
+
19
+ # Exactly-typed nested accessors. `cursus` may be an id or a fetched
20
+ # Cursus; the matching `Cursus.<name>` properties delegate here.
21
+
22
+ def users(self, cursus: int | Cursus) -> AsyncQuerySet[User]:
23
+ """Users in a cursus (``GET /cursus/{id}/users``)."""
24
+ return self._client.users._queryset(self._scoped_path(cursus, "users"))
25
+
26
+ def events(self, cursus: int | Cursus) -> AsyncQuerySet[Event]:
27
+ """Events of a cursus (``GET /cursus/{id}/events``)."""
28
+ return self._client.events._queryset(self._scoped_path(cursus, "events"))
29
+
30
+ def projects(self, cursus: int | Cursus) -> AsyncQuerySet[Project]:
31
+ """Projects of a cursus (``GET /cursus/{id}/projects``)."""
32
+ return self._client.projects._queryset(self._scoped_path(cursus, "projects"))
33
+
34
+ def _bind_relations(self, instance: Cursus) -> None:
35
+ instance._bind_relation("users", lambda: self.users(instance))
36
+ instance._bind_relation("events", lambda: self.events(instance))
37
+ instance._bind_relation("projects", lambda: self.projects(instance))
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ from ..._paths import path_segment
3
4
  from ...models.exam import Exam
4
5
  from .base import AsyncResource
5
6
 
@@ -16,8 +17,8 @@ class AsyncExamsResource(AsyncResource[Exam]):
16
17
  if interval is not None and field is None:
17
18
  field = "created_at"
18
19
  if field is not None:
19
- path += f"/on/{field}"
20
+ path += f"/on/{path_segment(field)}"
20
21
  if interval is not None:
21
- path += f"/by/{interval}"
22
+ path += f"/by/{path_segment(interval)}"
22
23
  response = await self._client.request("GET", path)
23
24
  return response.json()
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ from ..._paths import path_segment
3
4
  from ...models.location import Location
4
5
  from .base import AsyncResource
5
6
 
@@ -23,8 +24,8 @@ class AsyncLocationsResource(AsyncResource[Location]):
23
24
  if interval is not None and field is None:
24
25
  field = "begin_at"
25
26
  if field is not None:
26
- path += f"/on/{field}"
27
+ path += f"/on/{path_segment(field)}"
27
28
  if interval is not None:
28
- path += f"/by/{interval}"
29
+ path += f"/by/{path_segment(interval)}"
29
30
  response = await self._client.request("GET", path)
30
31
  return response.json()
@@ -0,0 +1,26 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from ...models.project import Project
6
+ from .base import AsyncResource
7
+
8
+ if TYPE_CHECKING:
9
+ from ...models.project_user import ProjectUser
10
+ from ..query import AsyncQuerySet
11
+
12
+
13
+ class AsyncProjectsResource(AsyncResource[Project]):
14
+ path = "/projects"
15
+ model = Project
16
+
17
+ def projects_users(self, project: int | Project) -> AsyncQuerySet[ProjectUser]:
18
+ """Assignments to a project (``GET /projects/{id}/projects_users``).
19
+
20
+ Referenced in the projects_users apidoc page.
21
+ ``Project.projects_users`` delegates here.
22
+ """
23
+ return self._client.projects_users._queryset(self._scoped_path(project, "projects_users"))
24
+
25
+ def _bind_relations(self, instance: Project) -> None:
26
+ instance._bind_relation("projects_users", lambda: self.projects_users(instance))
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ from ..._paths import path_segment
3
4
  from ...models.project_user import ProjectUser
4
5
  from .base import AsyncResource
5
6
 
@@ -15,8 +16,8 @@ class AsyncProjectUsersResource(AsyncResource[ProjectUser]):
15
16
  if interval is not None and field is None:
16
17
  field = "created_at"
17
18
  if field is not None:
18
- path += f"/on/{field}"
19
+ path += f"/on/{path_segment(field)}"
19
20
  if interval is not None:
20
- path += f"/by/{interval}"
21
+ path += f"/by/{path_segment(interval)}"
21
22
  response = await self._client.request("GET", path)
22
23
  return response.json()
@@ -0,0 +1,43 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from ...models.user import User
6
+ from .base import AsyncResource
7
+
8
+ if TYPE_CHECKING:
9
+ from ...models.campus_user import CampusUser
10
+ from ...models.event import Event
11
+ from ...models.location import Location
12
+ from ...models.project_user import ProjectUser
13
+ from ..query import AsyncQuerySet
14
+
15
+
16
+ class AsyncUsersResource(AsyncResource[User]):
17
+ path = "/users"
18
+ model = User
19
+
20
+ # Exactly-typed nested accessors. `user` may be an id, a login or a
21
+ # fetched User; the matching `User.<name>` properties delegate here.
22
+
23
+ def events(self, user: int | str | User) -> AsyncQuerySet[Event]:
24
+ """Events of a user (``GET /users/{id}/events``)."""
25
+ return self._client.events._queryset(self._scoped_path(user, "events"))
26
+
27
+ def campus_users(self, user: int | str | User) -> AsyncQuerySet[CampusUser]:
28
+ """Campus memberships of a user (``GET /users/{id}/campus_users``)."""
29
+ return self._client.campus_users._queryset(self._scoped_path(user, "campus_users"))
30
+
31
+ def locations(self, user: int | str | User) -> AsyncQuerySet[Location]:
32
+ """Login sessions of a user (``GET /users/{id}/locations``)."""
33
+ return self._client.locations._queryset(self._scoped_path(user, "locations"))
34
+
35
+ def projects_users(self, user: int | str | User) -> AsyncQuerySet[ProjectUser]:
36
+ """Project assignments of a user (``GET /users/{id}/projects_users``)."""
37
+ return self._client.projects_users._queryset(self._scoped_path(user, "projects_users"))
38
+
39
+ def _bind_relations(self, instance: User) -> None:
40
+ instance._bind_relation("events", lambda: self.events(instance))
41
+ instance._bind_relation("campus_users", lambda: self.campus_users(instance))
42
+ instance._bind_relation("locations", lambda: self.locations(instance))
43
+ instance._bind_relation("projects_users", lambda: self.projects_users(instance))
@@ -44,6 +44,12 @@ class TokenManager:
44
44
  def _is_valid(self) -> bool:
45
45
  return self._access_token is not None and time.time() < self._expires_at - self._leeway
46
46
 
47
+ def invalidate(self, token: str) -> None:
48
+ with self._lock:
49
+ if self._access_token == token:
50
+ self._access_token = None
51
+ self._expires_at = 0.0
52
+
47
53
  def _body(self) -> dict[str, str]:
48
54
  return {
49
55
  "grant_type": "client_credentials",
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  from dataclasses import dataclass
6
6
 
7
7
  DEFAULT_BASE_URL = "https://api.intra.42.fr/v2"
8
+ DEFAULT_PAGE_SIZE = 100
8
9
 
9
10
 
10
11
  @dataclass(slots=True)
@@ -12,6 +13,8 @@ class ClientConfig:
12
13
  base_url: str = DEFAULT_BASE_URL
13
14
  timeout: float = 10.0
14
15
  max_retries: int = 3
16
+ retry_backoff: float = 0.5
17
+ default_page_size: int | None = DEFAULT_PAGE_SIZE
15
18
  rate: float = 2.0
16
19
  burst: int = 2
17
20
  hourly_quota: int = 1200
@@ -0,0 +1,18 @@
1
+ """Pure helper for safely interpolating caller-supplied values into URL paths."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from urllib.parse import quote
6
+
7
+
8
+ def path_segment(value: int | str) -> str:
9
+ """Encode ``value`` as a single URL path segment.
10
+
11
+ Percent-encodes everything outside the unreserved set, including ``/``,
12
+ ``?`` and ``#``, so a value like ``"../campus/1"`` can't escape its
13
+ segment and hit a different endpoint.
14
+ """
15
+ text = str(value)
16
+ if text in ("", ".", ".."):
17
+ raise ValueError(f"Invalid path segment: {text!r}")
18
+ return quote(text, safe="")