Parcourir la source

Include the API version in responses

Jeremy Stretch il y a 8 ans
Parent
commit
54468ab1a8
3 fichiers modifiés avec 19 ajouts et 2 suppressions
  1. 1 0
      netbox/netbox/settings.py
  2. 1 1
      netbox/netbox/urls.py
  3. 17 1
      netbox/utilities/middleware.py

+ 1 - 0
netbox/netbox/settings.py

@@ -129,6 +129,7 @@ MIDDLEWARE = (
     'django.middleware.clickjacking.XFrameOptionsMiddleware',
     'django.middleware.security.SecurityMiddleware',
     'utilities.middleware.LoginRequiredMiddleware',
+    'utilities.middleware.APIVersionMiddleware',
 )
 
 ROOT_URLCONF = 'netbox.urls'

+ 1 - 1
netbox/netbox/urls.py

@@ -26,7 +26,7 @@ _patterns = [
     url(r'^user/', include('users.urls', namespace='user')),
 
     # API
-    url(r'^api/$', APIRootView.as_view()),
+    url(r'^api/$', APIRootView.as_view(), name='api-root'),
     url(r'^api/circuits/', include('circuits.api.urls', namespace='circuits-api')),
     url(r'^api/dcim/', include('dcim.api.urls', namespace='dcim-api')),
     url(r'^api/extras/', include('extras.api.urls', namespace='extras-api')),

+ 17 - 1
netbox/utilities/middleware.py

@@ -1,5 +1,6 @@
 from django.http import HttpResponseRedirect
 from django.conf import settings
+from django.core.urlresolvers import reverse
 
 
 BASE_PATH = getattr(settings, 'BASE_PATH', False)
@@ -17,7 +18,22 @@ class LoginRequiredMiddleware(object):
         if LOGIN_REQUIRED and not request.user.is_authenticated():
             # Redirect unauthenticated requests to the login page. API requests are exempt from redirection as the API
             # performs its own authentication.
-            api_path = '/{}api/'.format(BASE_PATH)
+            api_path = reverse('api-root')
             if not request.path_info.startswith(api_path) and request.path_info != settings.LOGIN_URL:
                 return HttpResponseRedirect('{}?next={}'.format(settings.LOGIN_URL, request.path_info))
         return self.get_response(request)
+
+
+class APIVersionMiddleware(object):
+    """
+    If the request is for an API endpoint, include the API version as a response header.
+    """
+    def __init__(self, get_response):
+        self.get_response = get_response
+
+    def __call__(self, request):
+        api_path = reverse('api-root')
+        response = self.get_response(request)
+        if request.path_info.startswith(api_path):
+            response['API-Version'] = settings.REST_FRAMEWORK_VERSION
+        return response