django-api-versioning 1.1.0__tar.gz → 1.2.1__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.1}/CHANGELOG.md +39 -0
- {django_api_versioning-1.1.0/django_api_versioning.egg-info → django_api_versioning-1.2.1}/PKG-INFO +30 -3
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/README.md +28 -1
- django_api_versioning-1.2.1/django_api_versioning/__init__.py +10 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/django_api_versioning/decorators.py +81 -0
- django_api_versioning-1.2.1/django_api_versioning/lifecycle.py +283 -0
- django_api_versioning-1.2.1/django_api_versioning/lifecycle_metadata.py +62 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/django_api_versioning/management/commands/check_versions.py +3 -1
- django_api_versioning-1.2.1/django_api_versioning/management/commands/migrate_endpoints.py +433 -0
- django_api_versioning-1.2.1/django_api_versioning/registry.py +684 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/django_api_versioning/routers.py +145 -5
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/django_api_versioning/settings.py +5 -1
- django_api_versioning-1.2.1/django_api_versioning/spectacular.py +75 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/django_api_versioning/testing.py +3 -1
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1/django_api_versioning.egg-info}/PKG-INFO +30 -3
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/django_api_versioning.egg-info/SOURCES.txt +5 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/django_api_versioning.egg-info/requires.txt +1 -1
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/pyproject.toml +2 -2
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/requirements-dev.txt +1 -1
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/tests/conftest.py +2 -2
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/tests/test_decorators.py +140 -2
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/tests/test_lifecycle.py +9 -7
- django_api_versioning-1.2.1/tests/test_lifecycle_integration.py +560 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/tests/test_management_commands.py +284 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/tests/test_registry.py +519 -4
- django_api_versioning-1.2.1/tests/test_route_removal.py +281 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/tests/test_routers.py +188 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/tests/test_settings.py +5 -0
- django_api_versioning-1.2.1/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.1}/LICENSE +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/MANIFEST.in +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/django_api_versioning/channels.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/django_api_versioning/exceptions.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/django_api_versioning/management/__init__.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/django_api_versioning/management/commands/__init__.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/django_api_versioning/py.typed +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/django_api_versioning/reverse.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/django_api_versioning/urls.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/django_api_versioning.egg-info/dependency_links.txt +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/django_api_versioning.egg-info/top_level.txt +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/pytest.ini +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/requirements.txt +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/setup.cfg +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/tests/__init__.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/tests/settings.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/tests/test_channels.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/tests/test_channels_extra.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/tests/test_distribution_contents.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/tests/test_exceptions.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/tests/test_reverse.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/tests/test_segment_model.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/tests/test_testing_utils.py +0 -0
- {django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/tests/test_urls.py +0 -0
|
@@ -7,6 +7,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.2.1] - 2026-11-19
|
|
11
|
+
|
|
12
|
+
### Documentation
|
|
13
|
+
|
|
14
|
+
- Refresh the PyPI long description and align published-version guidance with the 1.2.0 release.
|
|
15
|
+
- Restore the landing page’s original, more concise section flow while keeping product positioning in page metadata and documentation.
|
|
16
|
+
|
|
17
|
+
### Packaging
|
|
18
|
+
|
|
19
|
+
- Publish the documentation and project-metadata update as a patch release; no runtime behavior changes.
|
|
20
|
+
|
|
21
|
+
## [1.2.0] - 2026-11-19
|
|
22
|
+
|
|
23
|
+
### Added
|
|
24
|
+
|
|
25
|
+
- 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.
|
|
26
|
+
- 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.
|
|
27
|
+
- 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.
|
|
28
|
+
|
|
29
|
+
### Fixed
|
|
30
|
+
|
|
31
|
+
- 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.
|
|
32
|
+
- Validate non-string and unhashable `API_VERSION_LIFECYCLE` status values as `VersioningError` instead of leaking a raw `TypeError`.
|
|
33
|
+
|
|
34
|
+
### Compatibility
|
|
35
|
+
|
|
36
|
+
- 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.
|
|
37
|
+
- 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.
|
|
38
|
+
- Header/query/tenant-based version negotiation remains unsupported; reserved settings do not activate additional negotiation channels.
|
|
39
|
+
|
|
40
|
+
### Verification
|
|
41
|
+
|
|
42
|
+
- 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.
|
|
43
|
+
|
|
44
|
+
### Documentation
|
|
45
|
+
|
|
46
|
+
- Update the canonical routing contract, public API reference, README, website, and ViewSet/lifecycle/OpenAPI design records for the 1.2.0 release boundary.
|
|
47
|
+
|
|
10
48
|
## [1.1.0] - 2026-11-18
|
|
11
49
|
|
|
12
50
|
### Added
|
|
@@ -22,6 +60,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
22
60
|
|
|
23
61
|
### Fixed
|
|
24
62
|
|
|
63
|
+
- 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
64
|
- 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
65
|
- 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
66
|
- `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.1}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: django-api-versioning
|
|
3
|
-
Version: 1.1
|
|
3
|
+
Version: 1.2.1
|
|
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,31 @@ 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
|
+
### How it complements Django REST Framework
|
|
124
|
+
|
|
125
|
+
DRF and this package solve related but different parts of API versioning:
|
|
126
|
+
|
|
127
|
+
| Responsibility | Django REST Framework | django-api-versioning |
|
|
128
|
+
|---|---|---|
|
|
129
|
+
| Identify a requested version | Built-in schemes such as URL path, namespace, query parameter, hostname, and Accept header | Selects registered implementations through concrete URL-path routes; VersionedRouterVersioning exposes the matched ViewSet namespace as request.version |
|
|
130
|
+
| Generate ViewSet routes | SimpleRouter and DefaultRouter generate actions and URL patterns | VersionedRouter integrates DRF SimpleRouter patterns with the package registry |
|
|
131
|
+
| Select a different implementation per version | Application code or separately maintained URL configurations | Declarative endpoint registration and per-generated-route inheritance/replacement |
|
|
132
|
+
| Carry unchanged endpoints forward | Application-managed | Built in to the registry |
|
|
133
|
+
| Inspect and guard the effective route matrix | Application-managed | check_versions and assert_version_matrix |
|
|
134
|
+
|
|
135
|
+
Use DRF's own versioning schemes when request-version identification is all you need. Use ordinary DRF routers when you want to manage each version's URL configuration yourself. Choose this package when you want a central registry to map concrete URL routes to version-specific implementations and carry unchanged routes forward. For ViewSets, use VersionedRouter; for Django views, APIView, and GenericAPIView, use @endpoint.
|
|
136
|
+
|
|
137
|
+
### What it does not do
|
|
138
|
+
|
|
139
|
+
- It does not negotiate versions through request headers, query parameters, hostnames, or tenants. The related channel/resolver settings are reserved and do not activate dispatch.
|
|
140
|
+
- It does not transform serializers or response payloads, guarantee semantic backward compatibility, or replace application contract tests.
|
|
141
|
+
- It does not decorate DRF ViewSet classes directly with @endpoint; use VersionedRouter for package-managed SimpleRouter integration.
|
|
142
|
+
- It does not provide DefaultRouter API-root/format-suffix parity, automatic endpoint-module discovery, or a built-in version-discovery endpoint.
|
|
143
|
+
- It does not generate a separate OpenAPI schema for each API version. The repository's executable OpenAPI example is validation tooling, not a package runtime dependency.
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
**Available since 1.2.0:** Explicit endpoint removal is supported through remove_endpoint() for decorator endpoints and VersionedRouter.remove() for generated DRF actions. Earlier versions retain the route, removed versions return 404, and a later declaration can explicitly reintroduce it. Version 1.2.0 also adds set_endpoint_lifecycle() for decorator endpoints and VersionedRouter.set_lifecycle() for DRF operations. The optional EndpointLifecycleAutoSchema integration marks matching deprecated OpenAPI operations. See the endpoint-removal and endpoint-lifecycle design documents.
|
|
147
|
+
|
|
123
148
|
## Why use it with Django REST Framework?
|
|
124
149
|
|
|
125
150
|
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 +236,7 @@ For endpoints that should exist only in selected versions, pass `versions=[1, 3]
|
|
|
211
236
|
|
|
212
237
|
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
238
|
|
|
214
|
-
**Scope:** the initial integration supports DRF
|
|
239
|
+
**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() (available since 1.2.0). Header/query/tenant negotiation is not enabled by the reserved settings and remains a separate design decision.
|
|
215
240
|
|
|
216
241
|
For DRF installation, use a version compatible with your Django release:
|
|
217
242
|
```bash
|
|
@@ -224,6 +249,8 @@ pip install "djangorestframework>=3.18.3,<3.19"
|
|
|
224
249
|
|
|
225
250
|
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
251
|
|
|
252
|
+
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.
|
|
253
|
+
|
|
227
254
|
## Requirements
|
|
228
255
|
|
|
229
256
|
- Python 3.10+
|
|
@@ -70,6 +70,31 @@ 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
|
+
### How it complements Django REST Framework
|
|
74
|
+
|
|
75
|
+
DRF and this package solve related but different parts of API versioning:
|
|
76
|
+
|
|
77
|
+
| Responsibility | Django REST Framework | django-api-versioning |
|
|
78
|
+
|---|---|---|
|
|
79
|
+
| Identify a requested version | Built-in schemes such as URL path, namespace, query parameter, hostname, and Accept header | Selects registered implementations through concrete URL-path routes; VersionedRouterVersioning exposes the matched ViewSet namespace as request.version |
|
|
80
|
+
| Generate ViewSet routes | SimpleRouter and DefaultRouter generate actions and URL patterns | VersionedRouter integrates DRF SimpleRouter patterns with the package registry |
|
|
81
|
+
| Select a different implementation per version | Application code or separately maintained URL configurations | Declarative endpoint registration and per-generated-route inheritance/replacement |
|
|
82
|
+
| Carry unchanged endpoints forward | Application-managed | Built in to the registry |
|
|
83
|
+
| Inspect and guard the effective route matrix | Application-managed | check_versions and assert_version_matrix |
|
|
84
|
+
|
|
85
|
+
Use DRF's own versioning schemes when request-version identification is all you need. Use ordinary DRF routers when you want to manage each version's URL configuration yourself. Choose this package when you want a central registry to map concrete URL routes to version-specific implementations and carry unchanged routes forward. For ViewSets, use VersionedRouter; for Django views, APIView, and GenericAPIView, use @endpoint.
|
|
86
|
+
|
|
87
|
+
### What it does not do
|
|
88
|
+
|
|
89
|
+
- It does not negotiate versions through request headers, query parameters, hostnames, or tenants. The related channel/resolver settings are reserved and do not activate dispatch.
|
|
90
|
+
- It does not transform serializers or response payloads, guarantee semantic backward compatibility, or replace application contract tests.
|
|
91
|
+
- It does not decorate DRF ViewSet classes directly with @endpoint; use VersionedRouter for package-managed SimpleRouter integration.
|
|
92
|
+
- It does not provide DefaultRouter API-root/format-suffix parity, automatic endpoint-module discovery, or a built-in version-discovery endpoint.
|
|
93
|
+
- It does not generate a separate OpenAPI schema for each API version. The repository's executable OpenAPI example is validation tooling, not a package runtime dependency.
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
**Available since 1.2.0:** Explicit endpoint removal is supported through remove_endpoint() for decorator endpoints and VersionedRouter.remove() for generated DRF actions. Earlier versions retain the route, removed versions return 404, and a later declaration can explicitly reintroduce it. Version 1.2.0 also adds set_endpoint_lifecycle() for decorator endpoints and VersionedRouter.set_lifecycle() for DRF operations. The optional EndpointLifecycleAutoSchema integration marks matching deprecated OpenAPI operations. See the endpoint-removal and endpoint-lifecycle design documents.
|
|
97
|
+
|
|
73
98
|
## Why use it with Django REST Framework?
|
|
74
99
|
|
|
75
100
|
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 +186,7 @@ For endpoints that should exist only in selected versions, pass `versions=[1, 3]
|
|
|
161
186
|
|
|
162
187
|
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
188
|
|
|
164
|
-
**Scope:** the initial integration supports DRF
|
|
189
|
+
**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() (available since 1.2.0). Header/query/tenant negotiation is not enabled by the reserved settings and remains a separate design decision.
|
|
165
190
|
|
|
166
191
|
For DRF installation, use a version compatible with your Django release:
|
|
167
192
|
```bash
|
|
@@ -174,6 +199,8 @@ pip install "djangorestframework>=3.18.3,<3.19"
|
|
|
174
199
|
|
|
175
200
|
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
201
|
|
|
202
|
+
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.
|
|
203
|
+
|
|
177
204
|
## Requirements
|
|
178
205
|
|
|
179
206
|
- Python 3.10+
|
{django_api_versioning-1.1.0 → django_api_versioning-1.2.1}/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__
|