mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-08-07 22:04:48 +03:00
Merge fa6b80ef18
into ebf43346a1
This commit is contained in:
commit
40fc6a2a3d
|
@ -64,19 +64,19 @@ class SchemaGenerator(object):
|
||||||
|
|
||||||
def get_schema(self, request=None):
|
def get_schema(self, request=None):
|
||||||
if self.endpoints is None:
|
if self.endpoints is None:
|
||||||
self.endpoints = self.get_api_endpoints(self.patterns)
|
endpoints = self.get_api_endpoints(self.patterns)
|
||||||
|
self.endpoints = self.add_categories(endpoints)
|
||||||
|
|
||||||
links = []
|
links = []
|
||||||
for path, method, category, action, callback in self.endpoints:
|
for path, method, category, action, callback in self.endpoints:
|
||||||
view = callback.cls()
|
view = self.get_view(callback)
|
||||||
for attr, val in getattr(callback, 'initkwargs', {}).items():
|
|
||||||
setattr(view, attr, val)
|
|
||||||
view.args = ()
|
view.args = ()
|
||||||
view.kwargs = {}
|
view.kwargs = {}
|
||||||
view.format_kwarg = None
|
view.format_kwarg = None
|
||||||
|
|
||||||
if request is not None:
|
if request is not None:
|
||||||
view.request = clone_request(request, method)
|
view.request = clone_request(request, method)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
view.check_permissions(view.request)
|
view.check_permissions(view.request)
|
||||||
except exceptions.APIException:
|
except exceptions.APIException:
|
||||||
|
@ -128,7 +128,7 @@ class SchemaGenerator(object):
|
||||||
)
|
)
|
||||||
api_endpoints.extend(nested_endpoints)
|
api_endpoints.extend(nested_endpoints)
|
||||||
|
|
||||||
return self.add_categories(api_endpoints)
|
return api_endpoints
|
||||||
|
|
||||||
def add_categories(self, api_endpoints):
|
def add_categories(self, api_endpoints):
|
||||||
"""
|
"""
|
||||||
|
@ -144,6 +144,15 @@ class SchemaGenerator(object):
|
||||||
for (path, method, action, callback) in api_endpoints
|
for (path, method, action, callback) in api_endpoints
|
||||||
]
|
]
|
||||||
|
|
||||||
|
def get_view(self, callback):
|
||||||
|
"""
|
||||||
|
Return constructed view with respect of overrided attributes by detail_route and list_route
|
||||||
|
"""
|
||||||
|
view = callback.cls()
|
||||||
|
for attr, val in getattr(callback, 'initkwargs', {}).items():
|
||||||
|
setattr(view, attr, val)
|
||||||
|
return view
|
||||||
|
|
||||||
def get_path(self, path_regex):
|
def get_path(self, path_regex):
|
||||||
"""
|
"""
|
||||||
Given a URL conf regex, return a URI template string.
|
Given a URL conf regex, return a URI template string.
|
||||||
|
@ -174,9 +183,10 @@ class SchemaGenerator(object):
|
||||||
if hasattr(callback, 'actions'):
|
if hasattr(callback, 'actions'):
|
||||||
return [method.upper() for method in callback.actions.keys()]
|
return [method.upper() for method in callback.actions.keys()]
|
||||||
|
|
||||||
|
view = self.get_view(callback)
|
||||||
return [
|
return [
|
||||||
method for method in
|
method for method in
|
||||||
callback.cls().allowed_methods if method not in ('OPTIONS', 'HEAD')
|
view.allowed_methods if method not in ('OPTIONS', 'HEAD')
|
||||||
]
|
]
|
||||||
|
|
||||||
def get_action(self, path, method, callback):
|
def get_action(self, path, method, callback):
|
||||||
|
|
|
@ -9,7 +9,7 @@ from rest_framework.decorators import detail_route, list_route
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.routers import DefaultRouter
|
from rest_framework.routers import DefaultRouter
|
||||||
from rest_framework.schemas import SchemaGenerator
|
from rest_framework.schemas import SchemaGenerator
|
||||||
from rest_framework.test import APIClient
|
from rest_framework.test import APIClient, APIRequestFactory
|
||||||
from rest_framework.views import APIView
|
from rest_framework.views import APIView
|
||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
|
|
||||||
|
@ -33,15 +33,25 @@ class AnotherSerializer(serializers.Serializer):
|
||||||
d = serializers.CharField(required=False)
|
d = serializers.CharField(required=False)
|
||||||
|
|
||||||
|
|
||||||
|
class ForbidAll(permissions.BasePermission):
|
||||||
|
def has_permission(self, request, view):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
class ExampleViewSet(ModelViewSet):
|
class ExampleViewSet(ModelViewSet):
|
||||||
pagination_class = ExamplePagination
|
pagination_class = ExamplePagination
|
||||||
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
|
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
|
||||||
filter_backends = [filters.OrderingFilter]
|
filter_backends = [filters.OrderingFilter]
|
||||||
serializer_class = ExampleSerializer
|
serializer_class = ExampleSerializer
|
||||||
|
|
||||||
@detail_route(methods=['post'], serializer_class=AnotherSerializer)
|
@detail_route(methods=['put', 'post'],
|
||||||
|
serializer_class=AnotherSerializer)
|
||||||
def custom_action(self, request, pk):
|
def custom_action(self, request, pk):
|
||||||
return super(ExampleSerializer, self).retrieve(self, request)
|
return super(ExampleSerializer, self).update(self, request)
|
||||||
|
|
||||||
|
@detail_route(permission_classes=[ForbidAll])
|
||||||
|
def forbidden_action(self, request, pk):
|
||||||
|
return super(ExampleSerializer, self).update(self, request)
|
||||||
|
|
||||||
@list_route()
|
@list_route()
|
||||||
def custom_list_action(self, request):
|
def custom_list_action(self, request):
|
||||||
|
@ -52,6 +62,15 @@ class ExampleViewSet(ModelViewSet):
|
||||||
return super(ExampleViewSet, self).get_serializer(*args, **kwargs)
|
return super(ExampleViewSet, self).get_serializer(*args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class RestrictiveViewSet(ModelViewSet):
|
||||||
|
permission_classes = [ForbidAll]
|
||||||
|
serializer_class = ExampleSerializer
|
||||||
|
|
||||||
|
@detail_route(methods=['put'], permission_classes=[permissions.AllowAny])
|
||||||
|
def allowed_action(self, request):
|
||||||
|
return super(RestrictiveViewSet, self).update(self, request)
|
||||||
|
|
||||||
|
|
||||||
class ExampleView(APIView):
|
class ExampleView(APIView):
|
||||||
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
|
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
|
||||||
|
|
||||||
|
@ -67,7 +86,14 @@ router.register('example', ExampleViewSet, base_name='example')
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
url(r'^', include(router.urls))
|
url(r'^', include(router.urls))
|
||||||
]
|
]
|
||||||
urlpatterns2 = [
|
|
||||||
|
router = DefaultRouter(schema_title='Restrictive API' if coreapi else None)
|
||||||
|
router.register('example', RestrictiveViewSet, base_name='example')
|
||||||
|
urlpatterns_restrict = [
|
||||||
|
url(r'^', include(router.urls))
|
||||||
|
]
|
||||||
|
|
||||||
|
urlpatterns_view = [
|
||||||
url(r'^example-view/$', ExampleView.as_view(), name='example-view')
|
url(r'^example-view/$', ExampleView.as_view(), name='example-view')
|
||||||
]
|
]
|
||||||
|
|
||||||
|
@ -142,6 +168,16 @@ class TestRouterGeneratedSchema(TestCase):
|
||||||
coreapi.Field('pk', required=True, location='path')
|
coreapi.Field('pk', required=True, location='path')
|
||||||
]
|
]
|
||||||
),
|
),
|
||||||
|
'custom_action': coreapi.Link(
|
||||||
|
url='/example/{pk}/custom_action/',
|
||||||
|
action='put',
|
||||||
|
encoding='application/json',
|
||||||
|
fields=[
|
||||||
|
coreapi.Field('pk', required=True, location='path'),
|
||||||
|
coreapi.Field('c', required=True, location='form'),
|
||||||
|
coreapi.Field('d', required=False, location='form'),
|
||||||
|
]
|
||||||
|
),
|
||||||
'custom_action': coreapi.Link(
|
'custom_action': coreapi.Link(
|
||||||
url='/example/{pk}/custom_action/',
|
url='/example/{pk}/custom_action/',
|
||||||
action='post',
|
action='post',
|
||||||
|
@ -189,10 +225,39 @@ class TestRouterGeneratedSchema(TestCase):
|
||||||
self.assertEqual(response.data, expected)
|
self.assertEqual(response.data, expected)
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(coreapi, 'coreapi is not installed')
|
||||||
|
class TestSchemaForRestrictedMethods(TestCase):
|
||||||
|
def test_resctricted_methods(self):
|
||||||
|
schema_generator = SchemaGenerator(title='Restrictive API', patterns=urlpatterns_restrict)
|
||||||
|
factory = APIRequestFactory()
|
||||||
|
from rest_framework.request import Request
|
||||||
|
mock_request = factory.get('/')
|
||||||
|
schema = schema_generator.get_schema(request=Request(mock_request))
|
||||||
|
expected = coreapi.Document(
|
||||||
|
url='',
|
||||||
|
title='Restrictive API',
|
||||||
|
content={
|
||||||
|
'example': {
|
||||||
|
'allowed_action': coreapi.Link(
|
||||||
|
url='/example/{pk}/allowed_action/',
|
||||||
|
action='put',
|
||||||
|
encoding='application/json',
|
||||||
|
fields=[
|
||||||
|
coreapi.Field('pk', required=True, location='path'),
|
||||||
|
coreapi.Field('a', required=True, location='form', description='A field description'),
|
||||||
|
coreapi.Field('b', required=False, location='form')
|
||||||
|
]
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
self.assertEqual(schema, expected)
|
||||||
|
|
||||||
|
|
||||||
@unittest.skipUnless(coreapi, 'coreapi is not installed')
|
@unittest.skipUnless(coreapi, 'coreapi is not installed')
|
||||||
class TestSchemaGenerator(TestCase):
|
class TestSchemaGenerator(TestCase):
|
||||||
def test_view(self):
|
def test_view(self):
|
||||||
schema_generator = SchemaGenerator(title='Test View', patterns=urlpatterns2)
|
schema_generator = SchemaGenerator(title='Test View', patterns=urlpatterns_view)
|
||||||
schema = schema_generator.get_schema()
|
schema = schema_generator.get_schema()
|
||||||
expected = coreapi.Document(
|
expected = coreapi.Document(
|
||||||
url='',
|
url='',
|
||||||
|
|
Loading…
Reference in New Issue
Block a user