django-api-versioning 1.1.0__tar.gz → 1.2.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.
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/CHANGELOG.md +28 -0
- {django_api_versioning-1.1.0/django_api_versioning.egg-info → django_api_versioning-1.2.0}/PKG-INFO +7 -3
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/README.md +5 -1
- django_api_versioning-1.2.0/django_api_versioning/__init__.py +10 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/django_api_versioning/decorators.py +81 -0
- django_api_versioning-1.2.0/django_api_versioning/lifecycle.py +283 -0
- django_api_versioning-1.2.0/django_api_versioning/lifecycle_metadata.py +62 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/django_api_versioning/management/commands/check_versions.py +3 -1
- django_api_versioning-1.2.0/django_api_versioning/management/commands/migrate_endpoints.py +433 -0
- django_api_versioning-1.2.0/django_api_versioning/registry.py +684 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/django_api_versioning/routers.py +145 -5
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/django_api_versioning/settings.py +5 -1
- django_api_versioning-1.2.0/django_api_versioning/spectacular.py +75 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/django_api_versioning/testing.py +3 -1
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0/django_api_versioning.egg-info}/PKG-INFO +7 -3
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/django_api_versioning.egg-info/SOURCES.txt +5 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/django_api_versioning.egg-info/requires.txt +1 -1
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/pyproject.toml +2 -2
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/requirements-dev.txt +1 -1
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/tests/conftest.py +2 -2
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/tests/test_decorators.py +140 -2
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/tests/test_lifecycle.py +9 -7
- django_api_versioning-1.2.0/tests/test_lifecycle_integration.py +560 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/tests/test_management_commands.py +284 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/tests/test_registry.py +519 -4
- django_api_versioning-1.2.0/tests/test_route_removal.py +281 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/tests/test_routers.py +188 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/tests/test_settings.py +5 -0
- django_api_versioning-1.2.0/tests/test_spectacular.py +172 -0
- django_api_versioning-1.1.0/django_api_versioning/__init__.py +0 -4
- django_api_versioning-1.1.0/django_api_versioning/lifecycle.py +0 -205
- django_api_versioning-1.1.0/django_api_versioning/management/commands/migrate_endpoints.py +0 -249
- django_api_versioning-1.1.0/django_api_versioning/registry.py +0 -244
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/LICENSE +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/MANIFEST.in +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/django_api_versioning/channels.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/django_api_versioning/exceptions.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/django_api_versioning/management/__init__.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/django_api_versioning/management/commands/__init__.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/django_api_versioning/py.typed +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/django_api_versioning/reverse.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/django_api_versioning/urls.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/django_api_versioning.egg-info/dependency_links.txt +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/django_api_versioning.egg-info/top_level.txt +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/pytest.ini +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/requirements.txt +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/setup.cfg +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/tests/__init__.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/tests/settings.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/tests/test_channels.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/tests/test_channels_extra.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/tests/test_distribution_contents.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/tests/test_exceptions.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/tests/test_reverse.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/tests/test_segment_model.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/tests/test_testing_utils.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/tests/test_urls.py +0 -0
|
@@ -7,6 +7,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.2.0] - 2026-11-19
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Add explicit endpoint removal through `remove_endpoint()` and `VersionedRouter.remove()`. Removed routes remain available in earlier API versions, disappear from runtime routing and URL reversal at the removal boundary, and may be explicitly reintroduced by a later version declaration.
|
|
15
|
+
- Add endpoint-level lifecycle declarations through `set_endpoint_lifecycle()` and `VersionedRouter.set_lifecycle()`. Matching requests receive version-scoped RFC 9745 `Deprecation` and RFC 8594 `Sunset` headers. The optional drf-spectacular adapter marks deprecated operations with OpenAPI `deprecated: true`. Endpoint-level past-Sunset metadata remains headers-only; version-wide retirement keeps its existing 410 behavior.
|
|
16
|
+
- Add the optional `EndpointLifecycleAutoSchema` integration for decorator-backed DRF endpoints and VersionedRouter operations. drf-spectacular remains an optional integration dependency and is not imported by the package core.
|
|
17
|
+
|
|
18
|
+
### Fixed
|
|
19
|
+
|
|
20
|
+
- Reject duplicate generated route patterns registered by different `VersionedRouter` instances instead of silently allowing the later router to replace the earlier ViewSet in the shared registry.
|
|
21
|
+
- Validate non-string and unhashable `API_VERSION_LIFECYCLE` status values as `VersioningError` instead of leaking a raw `TypeError`.
|
|
22
|
+
|
|
23
|
+
### Compatibility
|
|
24
|
+
|
|
25
|
+
- No migration is required for existing 1.1.0 users. The existing URL-path routing contract and the optional nature of Django REST Framework are unchanged.
|
|
26
|
+
- Applications that registered colliding generated route patterns across independent `VersionedRouter` instances will now receive `VersioningError` instead of relying on last-writer replacement. Use distinct route prefixes and outer namespaces; duplicate generated patterns are not a supported dispatch contract.
|
|
27
|
+
- Header/query/tenant-based version negotiation remains unsupported; reserved settings do not activate additional negotiation channels.
|
|
28
|
+
|
|
29
|
+
### Verification
|
|
30
|
+
|
|
31
|
+
- Release verification is tied to the annotated `v1.2.0` tag and its GitHub Actions run. The full Python/Django/DRF matrix, executable versioned OpenAPI consumer contract, wheel/sdist validation, isolated installed-wheel smoke test, and distribution-content checks are required before publication.
|
|
32
|
+
|
|
33
|
+
### Documentation
|
|
34
|
+
|
|
35
|
+
- Update the canonical routing contract, public API reference, README, website, and ViewSet/lifecycle/OpenAPI design records for the 1.2.0 release boundary.
|
|
36
|
+
|
|
10
37
|
## [1.1.0] - 2026-11-18
|
|
11
38
|
|
|
12
39
|
### Added
|
|
@@ -22,6 +49,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
22
49
|
|
|
23
50
|
### Fixed
|
|
24
51
|
|
|
52
|
+
- Make `VersionedRouterVersioning` interoperable with drf-spectacular's namespace version filtering while preserving package-specific reversal; avoid double namespace qualification and defer SimpleRouter import to prevent a DRF initialization cycle.
|
|
25
53
|
- Add opt-in strict route-matrix assertions that reject empty registries and missing committed snapshots while preserving existing default behavior; add `check_versions --fail-on-empty` and resolve root and included URLconfs before inspecting registered endpoints.
|
|
26
54
|
- Reject deprecated or retired lifecycle configurations where `sunset` is earlier than `deprecated_at`, comparing dates as UTC instants and interpreting timezone-naive ISO 8601 values as UTC.
|
|
27
55
|
- `LifecycleMiddleware` now sends the `Sunset` header (and `Deprecation`, when `deprecated_at` is configured) for `retired` versions whose `sunset` date is still in the future. Previously these responses carried no lifecycle headers even though the version was about to be removed. Retired versions with a past `sunset` still return `410 Gone`, and `active` and unknown versions are unchanged.
|
{django_api_versioning-1.1.0/django_api_versioning.egg-info → django_api_versioning-1.2.0}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: django-api-versioning
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.2.0
|
|
4
4
|
Summary: URL-path API versioning for Django and Django REST Framework with decorator-based endpoint registration and forward route inheritance.
|
|
5
5
|
Author-email: Mojtaba Arvin <ArvinDevDay@gmail.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -45,7 +45,7 @@ Requires-Dist: pre-commit>=4.7.0; python_version >= "3.11" and extra == "dev"
|
|
|
45
45
|
Requires-Dist: twine>=7.0.0; extra == "dev"
|
|
46
46
|
Requires-Dist: build>=1.6.1; extra == "dev"
|
|
47
47
|
Requires-Dist: djangorestframework>=3.18; extra == "dev"
|
|
48
|
-
Requires-Dist: tomli>=2.0
|
|
48
|
+
Requires-Dist: tomli>=2.5.0; python_version < "3.11" and extra == "dev"
|
|
49
49
|
Dynamic: license-file
|
|
50
50
|
|
|
51
51
|
<p align="center">
|
|
@@ -120,6 +120,8 @@ Django API Versioning makes that mapping explicit with `@endpoint`:
|
|
|
120
120
|
|
|
121
121
|
This is inheritance of route registrations, not automatic backward compatibility. Your application remains responsible for response schemas, business behavior, and compatibility tests.
|
|
122
122
|
|
|
123
|
+
**Included in the upcoming 1.2.0 release (not yet published):** Explicit endpoint removal is implemented in the repository and will be included in the next release; it is not part of the published `1.1.0` artifact. Use `remove_endpoint("orders/", from_version=3)` for decorator endpoints or `VersionedRouter.remove(prefix, route_name, from_version=...)` for one generated DRF action. Earlier versions retain the route, removed versions return 404, and a later source declaration can explicitly reintroduce it. These APIs are documented in the [endpoint-removal contract](https://github.com/mojtaba-arvin/django-api-versioning/blob/main/docs/design/endpoint-removal.md). The 1.2.0 release candidate also adds `set_endpoint_lifecycle()` for decorator endpoints and `VersionedRouter.set_lifecycle()` for DRF operations. The optional `EndpointLifecycleAutoSchema` integration marks matching deprecated OpenAPI operations; these endpoint-level lifecycle APIs are also included in the upcoming `1.2.0` release, pending publication. See the [endpoint lifecycle design](https://github.com/mojtaba-arvin/django-api-versioning/blob/main/docs/design/endpoint-lifecycle.md).
|
|
124
|
+
|
|
123
125
|
## Why use it with Django REST Framework?
|
|
124
126
|
|
|
125
127
|
DRF already provides request-version identification and ViewSet route generation. Django API Versioning adds the missing connection between those capabilities: **mapping each concrete API version to the correct ViewSet implementation while inheriting unchanged routes independently**.
|
|
@@ -211,7 +213,7 @@ For endpoints that should exist only in selected versions, pass `versions=[1, 3]
|
|
|
211
213
|
|
|
212
214
|
The adapter is required when ViewSets need `request.version`, `reverse_action()`, or hyperlinked serializer support. You can configure it globally through `REST_FRAMEWORK` as shown above, or set `versioning_class = VersionedRouterVersioning` on selected ViewSets.
|
|
213
215
|
|
|
214
|
-
**Scope:** the initial integration supports DRF `SimpleRouter`; it does not claim `DefaultRouter` API-root or format-suffix parity. It does not transform serializers or response payloads. A route omitted from a later ViewSet remains inherited;
|
|
216
|
+
**Scope:** the initial integration supports DRF `SimpleRouter`; it does not claim `DefaultRouter` API-root or format-suffix parity. It does not transform serializers or response payloads. A route omitted from a later ViewSet remains inherited; remove it explicitly with `VersionedRouter.remove()` (included in the upcoming 1.2.0 release, not in the published `1.1.0` artifact). Header/query/tenant negotiation is not enabled by the reserved settings and remains a separate design decision.
|
|
215
217
|
|
|
216
218
|
For DRF installation, use a version compatible with your Django release:
|
|
217
219
|
```bash
|
|
@@ -224,6 +226,8 @@ pip install "djangorestframework>=3.18.3,<3.19"
|
|
|
224
226
|
|
|
225
227
|
See the [Versioned DRF ViewSet guide](https://mojtaba-arvin.github.io/django-api-versioning/articles/025-django-api-versioning-viewset-support-limitations/) for route inheritance, reversal, namespaces, and the exact integration boundary.
|
|
226
228
|
|
|
229
|
+
For the repository's executable OpenAPI workflow, see the [versioned OpenAPI contract example](https://github.com/mojtaba-arvin/django-api-versioning/tree/main/examples/openapi_contract). This consumer example and its `oasdiff` CI gate were added after the published release; they are repository-level tooling, not part of the package wheel, and do not make drf-spectacular or oasdiff runtime dependencies.
|
|
230
|
+
|
|
227
231
|
## Requirements
|
|
228
232
|
|
|
229
233
|
- Python 3.10+
|
|
@@ -70,6 +70,8 @@ Django API Versioning makes that mapping explicit with `@endpoint`:
|
|
|
70
70
|
|
|
71
71
|
This is inheritance of route registrations, not automatic backward compatibility. Your application remains responsible for response schemas, business behavior, and compatibility tests.
|
|
72
72
|
|
|
73
|
+
**Included in the upcoming 1.2.0 release (not yet published):** Explicit endpoint removal is implemented in the repository and will be included in the next release; it is not part of the published `1.1.0` artifact. Use `remove_endpoint("orders/", from_version=3)` for decorator endpoints or `VersionedRouter.remove(prefix, route_name, from_version=...)` for one generated DRF action. Earlier versions retain the route, removed versions return 404, and a later source declaration can explicitly reintroduce it. These APIs are documented in the [endpoint-removal contract](https://github.com/mojtaba-arvin/django-api-versioning/blob/main/docs/design/endpoint-removal.md). The 1.2.0 release candidate also adds `set_endpoint_lifecycle()` for decorator endpoints and `VersionedRouter.set_lifecycle()` for DRF operations. The optional `EndpointLifecycleAutoSchema` integration marks matching deprecated OpenAPI operations; these endpoint-level lifecycle APIs are also included in the upcoming `1.2.0` release, pending publication. See the [endpoint lifecycle design](https://github.com/mojtaba-arvin/django-api-versioning/blob/main/docs/design/endpoint-lifecycle.md).
|
|
74
|
+
|
|
73
75
|
## Why use it with Django REST Framework?
|
|
74
76
|
|
|
75
77
|
DRF already provides request-version identification and ViewSet route generation. Django API Versioning adds the missing connection between those capabilities: **mapping each concrete API version to the correct ViewSet implementation while inheriting unchanged routes independently**.
|
|
@@ -161,7 +163,7 @@ For endpoints that should exist only in selected versions, pass `versions=[1, 3]
|
|
|
161
163
|
|
|
162
164
|
The adapter is required when ViewSets need `request.version`, `reverse_action()`, or hyperlinked serializer support. You can configure it globally through `REST_FRAMEWORK` as shown above, or set `versioning_class = VersionedRouterVersioning` on selected ViewSets.
|
|
163
165
|
|
|
164
|
-
**Scope:** the initial integration supports DRF `SimpleRouter`; it does not claim `DefaultRouter` API-root or format-suffix parity. It does not transform serializers or response payloads. A route omitted from a later ViewSet remains inherited;
|
|
166
|
+
**Scope:** the initial integration supports DRF `SimpleRouter`; it does not claim `DefaultRouter` API-root or format-suffix parity. It does not transform serializers or response payloads. A route omitted from a later ViewSet remains inherited; remove it explicitly with `VersionedRouter.remove()` (included in the upcoming 1.2.0 release, not in the published `1.1.0` artifact). Header/query/tenant negotiation is not enabled by the reserved settings and remains a separate design decision.
|
|
165
167
|
|
|
166
168
|
For DRF installation, use a version compatible with your Django release:
|
|
167
169
|
```bash
|
|
@@ -174,6 +176,8 @@ pip install "djangorestframework>=3.18.3,<3.19"
|
|
|
174
176
|
|
|
175
177
|
See the [Versioned DRF ViewSet guide](https://mojtaba-arvin.github.io/django-api-versioning/articles/025-django-api-versioning-viewset-support-limitations/) for route inheritance, reversal, namespaces, and the exact integration boundary.
|
|
176
178
|
|
|
179
|
+
For the repository's executable OpenAPI workflow, see the [versioned OpenAPI contract example](https://github.com/mojtaba-arvin/django-api-versioning/tree/main/examples/openapi_contract). This consumer example and its `oasdiff` CI gate were added after the published release; they are repository-level tooling, not part of the package wheel, and do not make drf-spectacular or oasdiff runtime dependencies.
|
|
180
|
+
|
|
177
181
|
## Requirements
|
|
178
182
|
|
|
179
183
|
- Python 3.10+
|
{django_api_versioning-1.1.0 → django_api_versioning-1.2.0}/django_api_versioning/decorators.py
RENAMED
|
@@ -84,6 +84,14 @@ def endpoint(
|
|
|
84
84
|
# Calculate logical endpoint ID from unversioned path
|
|
85
85
|
logical_endpoint = f"{app_name_part}{postfix}"
|
|
86
86
|
|
|
87
|
+
# The schema adapter for URLPathVersioning has no ResolverMatch. Carry
|
|
88
|
+
# the stable decorator identity on the view class, not on callback
|
|
89
|
+
# identity, so schema introspection can resolve it through the registry.
|
|
90
|
+
setattr(view, registry._LOGICAL_ENDPOINT_ATTR, logical_endpoint)
|
|
91
|
+
view_class = getattr(view, "cls", None)
|
|
92
|
+
if isinstance(view_class, type):
|
|
93
|
+
setattr(view_class, registry._LOGICAL_ENDPOINT_ATTR, logical_endpoint)
|
|
94
|
+
|
|
87
95
|
def _register_route(ver: int | None, source_version: int | None) -> None:
|
|
88
96
|
"""Helper function to register a route in the registry."""
|
|
89
97
|
if ver is None:
|
|
@@ -132,6 +140,61 @@ def endpoint(
|
|
|
132
140
|
return decorator
|
|
133
141
|
|
|
134
142
|
|
|
143
|
+
def set_endpoint_lifecycle(
|
|
144
|
+
postfix: str,
|
|
145
|
+
*,
|
|
146
|
+
version: int,
|
|
147
|
+
app_name: str | None = None,
|
|
148
|
+
methods: list[str] | None = None,
|
|
149
|
+
deprecated_at: str | None = None,
|
|
150
|
+
sunset: str | None = None,
|
|
151
|
+
) -> None:
|
|
152
|
+
"""Declare lifecycle dates for one concrete decorator endpoint version.
|
|
153
|
+
|
|
154
|
+
Unlike ``endpoint(version=N)``, this declaration applies only to the
|
|
155
|
+
explicit concrete ``version``. Omitting ``methods`` applies to every
|
|
156
|
+
HTTP method on the logical endpoint; providing methods narrows the scope.
|
|
157
|
+
"""
|
|
158
|
+
if not isinstance(postfix, str):
|
|
159
|
+
raise TypeError("postfix must be a string.")
|
|
160
|
+
if postfix.startswith("/"):
|
|
161
|
+
raise VersioningError("postfix must be relative and must not start with '/'.")
|
|
162
|
+
if app_name is not None and not isinstance(app_name, str):
|
|
163
|
+
raise TypeError("app_name must be a string or None.")
|
|
164
|
+
|
|
165
|
+
app_name_part = f"{app_name}/" if app_name else ""
|
|
166
|
+
logical_endpoint = f"{app_name_part}{postfix}"
|
|
167
|
+
|
|
168
|
+
if methods is None:
|
|
169
|
+
registry.register_endpoint_lifecycle(
|
|
170
|
+
logical_endpoint,
|
|
171
|
+
version,
|
|
172
|
+
deprecated_at=deprecated_at,
|
|
173
|
+
sunset=sunset,
|
|
174
|
+
)
|
|
175
|
+
return
|
|
176
|
+
|
|
177
|
+
if not isinstance(methods, list) or not methods:
|
|
178
|
+
raise VersioningError("methods must be a non-empty list of HTTP methods.")
|
|
179
|
+
normalized_methods = [
|
|
180
|
+
method.strip().upper() if isinstance(method, str) else method
|
|
181
|
+
for method in methods
|
|
182
|
+
]
|
|
183
|
+
if any(not isinstance(method, str) or not method for method in normalized_methods):
|
|
184
|
+
raise VersioningError("methods must contain non-empty HTTP method strings.")
|
|
185
|
+
if len(set(normalized_methods)) != len(normalized_methods):
|
|
186
|
+
raise VersioningError("methods must not contain duplicates.")
|
|
187
|
+
|
|
188
|
+
for method in normalized_methods:
|
|
189
|
+
registry.register_endpoint_lifecycle(
|
|
190
|
+
logical_endpoint,
|
|
191
|
+
version,
|
|
192
|
+
method=method,
|
|
193
|
+
deprecated_at=deprecated_at,
|
|
194
|
+
sunset=sunset,
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
|
|
135
198
|
def _validate_version(version: int, max_version: int) -> None:
|
|
136
199
|
if isinstance(version, bool) or not isinstance(version, int):
|
|
137
200
|
raise VersionTypeError("Version must be an integer.")
|
|
@@ -139,3 +202,21 @@ def _validate_version(version: int, max_version: int) -> None:
|
|
|
139
202
|
raise InvalidVersionError(
|
|
140
203
|
f"Version {version} is above the maximum allowed version {max_version}."
|
|
141
204
|
)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def remove_endpoint(
|
|
208
|
+
postfix: str,
|
|
209
|
+
*,
|
|
210
|
+
from_version: int,
|
|
211
|
+
app_name: str | None = None,
|
|
212
|
+
) -> None:
|
|
213
|
+
"""Remove a logical endpoint from a version onward.
|
|
214
|
+
|
|
215
|
+
A later declaration with a higher source version can reintroduce it.
|
|
216
|
+
"""
|
|
217
|
+
if not isinstance(postfix, str):
|
|
218
|
+
raise TypeError("postfix must be a string.")
|
|
219
|
+
if postfix.startswith("/"):
|
|
220
|
+
raise VersioningError("postfix must be relative and must not start with '/'.")
|
|
221
|
+
app_name_part = f"{app_name}/" if app_name else ""
|
|
222
|
+
registry.remove(f"{app_name_part}{postfix}", from_version)
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import re
|
|
3
|
+
from datetime import datetime, timezone
|
|
4
|
+
from typing import Any, Callable
|
|
5
|
+
|
|
6
|
+
from django.conf import settings as django_settings
|
|
7
|
+
from django.http import HttpRequest, HttpResponse, HttpResponseGone
|
|
8
|
+
|
|
9
|
+
from .registry import registry
|
|
10
|
+
from .settings import api_settings
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _get_api_setting(name: str, default: Any = None) -> Any:
|
|
16
|
+
"""
|
|
17
|
+
Get API setting from django.conf.settings at request time.
|
|
18
|
+
|
|
19
|
+
This ensures that override_settings in tests affects middleware behavior.
|
|
20
|
+
For backward compatibility with monkeypatch-based tests, also checks
|
|
21
|
+
the cached api_settings object if the setting is not found in django.conf.settings.
|
|
22
|
+
|
|
23
|
+
Falls back to default if setting is not configured in either location.
|
|
24
|
+
"""
|
|
25
|
+
if hasattr(django_settings, name):
|
|
26
|
+
return getattr(django_settings, name)
|
|
27
|
+
|
|
28
|
+
if hasattr(api_settings, name):
|
|
29
|
+
return getattr(api_settings, name)
|
|
30
|
+
|
|
31
|
+
return default
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class LifecycleMiddleware:
|
|
35
|
+
"""
|
|
36
|
+
Inject Deprecation / Sunset headers and enforce version-wide sunset.
|
|
37
|
+
|
|
38
|
+
Resolved requests use Django's actual resolver match. Unresolved requests
|
|
39
|
+
retain path-based lifecycle behavior only when the API version is
|
|
40
|
+
unambiguous.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, get_response: Callable) -> None:
|
|
44
|
+
self.get_response = get_response
|
|
45
|
+
|
|
46
|
+
def __call__(self, request: HttpRequest) -> HttpResponse:
|
|
47
|
+
response = self.get_response(request)
|
|
48
|
+
return self.process_response(request, response)
|
|
49
|
+
|
|
50
|
+
def process_view(
|
|
51
|
+
self,
|
|
52
|
+
request: HttpRequest,
|
|
53
|
+
view_func: Callable,
|
|
54
|
+
view_args: list,
|
|
55
|
+
view_kwargs: dict,
|
|
56
|
+
) -> HttpResponse | None:
|
|
57
|
+
"""Enforce sunset after URL resolution and before the selected view."""
|
|
58
|
+
state = _get_lifecycle_state(request)
|
|
59
|
+
if state is None:
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
version, meta, _, sunset_date = state
|
|
63
|
+
if not meta or sunset_date is None or not _is_past(sunset_date):
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
request._django_api_version_lifecycle_sunset_enforced = True
|
|
67
|
+
sunset = meta.get("sunset")
|
|
68
|
+
return HttpResponseGone(
|
|
69
|
+
f"API version {version} has been retired as of {sunset}."
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
def process_response(
|
|
73
|
+
self, request: HttpRequest, response: HttpResponse
|
|
74
|
+
) -> HttpResponse:
|
|
75
|
+
"""Apply lifecycle headers or preserve version-wide 410 behavior."""
|
|
76
|
+
state = _get_lifecycle_state(request)
|
|
77
|
+
version = None
|
|
78
|
+
meta = None
|
|
79
|
+
version_deprecation_date = None
|
|
80
|
+
version_sunset_date = None
|
|
81
|
+
|
|
82
|
+
if state is not None:
|
|
83
|
+
version, meta, version_deprecation_date, version_sunset_date = state
|
|
84
|
+
|
|
85
|
+
# Version-wide retirement remains authoritative and is evaluated
|
|
86
|
+
# before endpoint metadata. Endpoint Sunset never changes the status
|
|
87
|
+
# code or suppresses the existing version-wide 410 contract.
|
|
88
|
+
if meta and version_sunset_date is not None and _is_past(version_sunset_date):
|
|
89
|
+
if getattr(request, "_django_api_version_lifecycle_sunset_enforced", False):
|
|
90
|
+
return response
|
|
91
|
+
sunset = meta.get("sunset")
|
|
92
|
+
return HttpResponseGone(
|
|
93
|
+
f"API version {version} has been retired as of {sunset}."
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
endpoint_lifecycle = _get_endpoint_lifecycle_state(request)
|
|
97
|
+
if not meta and endpoint_lifecycle is None:
|
|
98
|
+
return response
|
|
99
|
+
|
|
100
|
+
deprecation_dates = []
|
|
101
|
+
sunset_dates = []
|
|
102
|
+
|
|
103
|
+
if meta:
|
|
104
|
+
status = meta.get("status")
|
|
105
|
+
if status in ("deprecated", "retired"):
|
|
106
|
+
if version_deprecation_date is not None:
|
|
107
|
+
deprecation_dates.append(version_deprecation_date)
|
|
108
|
+
elif status == "deprecated":
|
|
109
|
+
logger.warning(
|
|
110
|
+
"Deprecated API version %s has no valid deprecated_at date; "
|
|
111
|
+
"omitting the Deprecation header.",
|
|
112
|
+
version,
|
|
113
|
+
)
|
|
114
|
+
if version_sunset_date is not None:
|
|
115
|
+
sunset_dates.append(version_sunset_date)
|
|
116
|
+
|
|
117
|
+
if endpoint_lifecycle is not None:
|
|
118
|
+
if endpoint_lifecycle.deprecated_at is not None:
|
|
119
|
+
deprecation_dates.append(endpoint_lifecycle.deprecated_at)
|
|
120
|
+
if endpoint_lifecycle.sunset is not None:
|
|
121
|
+
sunset_dates.append(endpoint_lifecycle.sunset)
|
|
122
|
+
|
|
123
|
+
if deprecation_dates:
|
|
124
|
+
response["Deprecation"] = _to_structured_field_date(min(deprecation_dates))
|
|
125
|
+
if sunset_dates:
|
|
126
|
+
response["Sunset"] = _to_http_date(min(sunset_dates))
|
|
127
|
+
return response
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _get_lifecycle_state(
|
|
131
|
+
request: HttpRequest,
|
|
132
|
+
) -> tuple[int, dict | None, datetime | None, datetime | None] | None:
|
|
133
|
+
"""Resolve and cache lifecycle metadata once per request."""
|
|
134
|
+
if hasattr(request, "_django_api_version_lifecycle_state"):
|
|
135
|
+
return request._django_api_version_lifecycle_state
|
|
136
|
+
|
|
137
|
+
version = _extract_version(request)
|
|
138
|
+
if version is None:
|
|
139
|
+
return None
|
|
140
|
+
|
|
141
|
+
lifecycle = _get_api_setting("API_VERSION_LIFECYCLE", {})
|
|
142
|
+
meta = lifecycle.get(version)
|
|
143
|
+
if not meta:
|
|
144
|
+
state = (version, None, None, None)
|
|
145
|
+
else:
|
|
146
|
+
deprecated_at = meta.get("deprecated_at")
|
|
147
|
+
deprecation_date = (
|
|
148
|
+
_parse_lifecycle_date(deprecated_at, "deprecation")
|
|
149
|
+
if deprecated_at
|
|
150
|
+
else None
|
|
151
|
+
)
|
|
152
|
+
sunset = meta.get("sunset")
|
|
153
|
+
sunset_date = _parse_sunset(sunset) if sunset else None
|
|
154
|
+
state = (version, meta, deprecation_date, sunset_date)
|
|
155
|
+
|
|
156
|
+
request._django_api_version_lifecycle_state = state
|
|
157
|
+
return state
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _get_endpoint_lifecycle_state(request: HttpRequest):
|
|
161
|
+
"""Resolve endpoint lifecycle metadata from Django's actual URL match."""
|
|
162
|
+
if hasattr(request, "_django_api_endpoint_lifecycle_state"):
|
|
163
|
+
return request._django_api_endpoint_lifecycle_state
|
|
164
|
+
|
|
165
|
+
match = getattr(request, "resolver_match", None)
|
|
166
|
+
if match is None:
|
|
167
|
+
lifecycle = None
|
|
168
|
+
else:
|
|
169
|
+
operation = registry.resolve_operation(match, request.method)
|
|
170
|
+
lifecycle = (
|
|
171
|
+
registry.get_endpoint_lifecycle(operation)
|
|
172
|
+
if operation is not None
|
|
173
|
+
else None
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
request._django_api_endpoint_lifecycle_state = lifecycle
|
|
177
|
+
return lifecycle
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _coerce_version(value: Any) -> int | None:
|
|
181
|
+
"""Accept integer versions without truncating booleans or other numeric types."""
|
|
182
|
+
if isinstance(value, bool):
|
|
183
|
+
return None
|
|
184
|
+
if isinstance(value, int):
|
|
185
|
+
return value
|
|
186
|
+
if isinstance(value, str) and value.isdecimal():
|
|
187
|
+
return int(value)
|
|
188
|
+
return None
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _extract_version(request: HttpRequest) -> int | None:
|
|
192
|
+
"""Prefer the actual matched route over request/path heuristics."""
|
|
193
|
+
match = getattr(request, "resolver_match", None)
|
|
194
|
+
if match:
|
|
195
|
+
kwargs = getattr(match, "kwargs", {}) or {}
|
|
196
|
+
version = _coerce_version(kwargs.get("version"))
|
|
197
|
+
if version is not None:
|
|
198
|
+
return version
|
|
199
|
+
|
|
200
|
+
route = getattr(match, "route", None)
|
|
201
|
+
if isinstance(route, str):
|
|
202
|
+
version = registry.get_resolved_route_version(route)
|
|
203
|
+
if version is not None:
|
|
204
|
+
return _coerce_version(version)
|
|
205
|
+
version = _extract_version_from_value(route)
|
|
206
|
+
if version is not None:
|
|
207
|
+
return version
|
|
208
|
+
|
|
209
|
+
# Retain support for explicitly supplied request.version when no matched
|
|
210
|
+
# route metadata identifies a version.
|
|
211
|
+
version = _coerce_version(getattr(request, "version", None))
|
|
212
|
+
if version is not None:
|
|
213
|
+
return version
|
|
214
|
+
|
|
215
|
+
# Unresolved requests use a conservative path fallback. Multiple distinct
|
|
216
|
+
# version segments are ambiguous and must not select the wrong policy.
|
|
217
|
+
return _extract_version_from_path(request)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _extract_version_from_path(request: HttpRequest) -> int | None:
|
|
221
|
+
"""
|
|
222
|
+
Extract an unambiguous version from a static URL path.
|
|
223
|
+
|
|
224
|
+
This fallback is used for unresolved requests. A resolved request uses
|
|
225
|
+
ResolverMatch and registry route metadata instead.
|
|
226
|
+
"""
|
|
227
|
+
path = request.path_info or request.path or ""
|
|
228
|
+
return _extract_version_from_value(path)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _extract_version_from_value(value: str) -> int | None:
|
|
232
|
+
"""Extract one distinct version from a path or resolved route string."""
|
|
233
|
+
api_base_path = _get_api_setting("API_BASE_PATH", "api/v{version}/")
|
|
234
|
+
if not api_base_path or api_base_path.count("{version}") != 1:
|
|
235
|
+
return None
|
|
236
|
+
|
|
237
|
+
parts = api_base_path.split("{version}")
|
|
238
|
+
prefix = re.escape(parts[0].lstrip("/"))
|
|
239
|
+
suffix = re.escape(parts[1])
|
|
240
|
+
pattern = f"(?:^|/){prefix}(\\d+){suffix}"
|
|
241
|
+
|
|
242
|
+
try:
|
|
243
|
+
versions = {int(match.group(1)) for match in re.finditer(pattern, value)}
|
|
244
|
+
except (IndexError, ValueError, re.error):
|
|
245
|
+
return None
|
|
246
|
+
|
|
247
|
+
return next(iter(versions)) if len(versions) == 1 else None
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _parse_sunset(value: Any) -> datetime | None:
|
|
251
|
+
"""Parse a configured sunset value and normalize it to UTC."""
|
|
252
|
+
return _parse_lifecycle_date(value, "sunset")
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _parse_lifecycle_date(value: Any, field_name: str) -> datetime | None:
|
|
256
|
+
"""Parse an ISO 8601 lifecycle date and normalize it to UTC."""
|
|
257
|
+
if not isinstance(value, str):
|
|
258
|
+
logger.warning("Invalid %s date %r; ignoring.", field_name, value)
|
|
259
|
+
return None
|
|
260
|
+
|
|
261
|
+
try:
|
|
262
|
+
normalized_value = value[:-1] + "+00:00" if value.endswith("Z") else value
|
|
263
|
+
parsed = datetime.fromisoformat(normalized_value)
|
|
264
|
+
except ValueError:
|
|
265
|
+
logger.warning("Invalid %s date %r; ignoring.", field_name, value)
|
|
266
|
+
return None
|
|
267
|
+
|
|
268
|
+
if parsed.tzinfo is None:
|
|
269
|
+
return parsed.replace(tzinfo=timezone.utc)
|
|
270
|
+
return parsed.astimezone(timezone.utc)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _is_past(date: datetime) -> bool:
|
|
274
|
+
return date < datetime.now(timezone.utc)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _to_http_date(date: datetime) -> str:
|
|
278
|
+
return date.strftime("%a, %d %b %Y %H:%M:%S GMT")
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _to_structured_field_date(date: datetime) -> str:
|
|
282
|
+
"""Serialize an RFC 9745 Date as an RFC 9651 Structured Field Date."""
|
|
283
|
+
return f"@{int(date.timestamp())}"
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Normalized metadata and validation for endpoint lifecycle declarations."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
|
|
6
|
+
from .exceptions import VersioningError
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True, slots=True)
|
|
10
|
+
class EndpointLifecycle:
|
|
11
|
+
"""Deprecation and Sunset instants for one registered endpoint scope."""
|
|
12
|
+
|
|
13
|
+
deprecated_at: datetime | None
|
|
14
|
+
sunset: datetime | None
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _parse_date(value: str | None, field_name: str) -> datetime | None:
|
|
18
|
+
if value is None:
|
|
19
|
+
return None
|
|
20
|
+
if not isinstance(value, str):
|
|
21
|
+
raise VersioningError(
|
|
22
|
+
f"Endpoint lifecycle {field_name} must be an ISO 8601 string."
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
normalized = value[:-1] + "+00:00" if value.endswith("Z") else value
|
|
26
|
+
try:
|
|
27
|
+
parsed = datetime.fromisoformat(normalized)
|
|
28
|
+
except ValueError as exc:
|
|
29
|
+
raise VersioningError(
|
|
30
|
+
f"Endpoint lifecycle {field_name} must be a valid ISO 8601 date."
|
|
31
|
+
) from exc
|
|
32
|
+
|
|
33
|
+
if parsed.tzinfo is None:
|
|
34
|
+
return parsed.replace(tzinfo=timezone.utc)
|
|
35
|
+
return parsed.astimezone(timezone.utc)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def parse_endpoint_lifecycle(
|
|
39
|
+
deprecated_at: str | None,
|
|
40
|
+
sunset: str | None,
|
|
41
|
+
) -> EndpointLifecycle:
|
|
42
|
+
"""Parse and validate a lifecycle declaration, normalizing dates to UTC."""
|
|
43
|
+
if deprecated_at is None and sunset is None:
|
|
44
|
+
raise VersioningError(
|
|
45
|
+
"An endpoint lifecycle declaration requires deprecated_at or sunset."
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
deprecated_date = _parse_date(deprecated_at, "deprecated_at")
|
|
49
|
+
sunset_date = _parse_date(sunset, "sunset")
|
|
50
|
+
if (
|
|
51
|
+
deprecated_date is not None
|
|
52
|
+
and sunset_date is not None
|
|
53
|
+
and sunset_date < deprecated_date
|
|
54
|
+
):
|
|
55
|
+
raise VersioningError(
|
|
56
|
+
"Endpoint lifecycle sunset must not be earlier than deprecated_at."
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
return EndpointLifecycle(
|
|
60
|
+
deprecated_at=deprecated_date,
|
|
61
|
+
sunset=sunset_date,
|
|
62
|
+
)
|
|
@@ -2,7 +2,7 @@ from collections import defaultdict
|
|
|
2
2
|
|
|
3
3
|
from django.core.management.base import BaseCommand, CommandError
|
|
4
4
|
|
|
5
|
-
from ...registry import registry
|
|
5
|
+
from ...registry import REMOVED_ROUTE, registry
|
|
6
6
|
from ...testing import _load_root_urlconf
|
|
7
7
|
|
|
8
8
|
|
|
@@ -52,6 +52,8 @@ class Command(BaseCommand):
|
|
|
52
52
|
@staticmethod
|
|
53
53
|
def _get_callback_name(callback):
|
|
54
54
|
"""Resolve callback name, handling both functions and class-based views."""
|
|
55
|
+
if callback is REMOVED_ROUTE:
|
|
56
|
+
return "<removed>"
|
|
55
57
|
# Try to get from class-based view metadata first
|
|
56
58
|
if hasattr(callback, "view_class"):
|
|
57
59
|
return callback.view_class.__name__
|