From 43d3634e892e303ca377265d3176e8313f19563f Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 30 Sep 2012 15:55:24 +0100 Subject: Docs tweaking --- docs/api-guide/authentication.md | 8 ++++---- docs/api-guide/responses.md | 24 ++++++++++++++++++------ 2 files changed, 22 insertions(+), 10 deletions(-) (limited to 'docs') diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index f24c6a81..c6995360 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -39,6 +39,7 @@ You can also set the authentication policy on a per-view basis, using the `APIVi class ExampleView(APIView): authentication_classes = (SessionAuthentication, UserBasicAuthentication) + permission_classes = (IsAuthenticated,) def get(self, request, format=None): content = { @@ -49,10 +50,9 @@ You can also set the authentication policy on a per-view basis, using the `APIVi Or, if you're using the `@api_view` decorator with function based views. - @api_view( - allowed=('GET',), - authentication_classes=(SessionAuthentication, UserBasicAuthentication) - ) + @api_view('GET'), + @authentication_classes(SessionAuthentication, UserBasicAuthentication) + @permissions_classes(IsAuthenticated) def example_view(request, format=None): content = { 'user': unicode(request.user), # `django.contrib.auth.User` instance. diff --git a/docs/api-guide/responses.md b/docs/api-guide/responses.md index 6c279f17..e9ebcf81 100644 --- a/docs/api-guide/responses.md +++ b/docs/api-guide/responses.md @@ -8,18 +8,30 @@ REST framework supports HTTP content negotiation by providing a `Response` class which allows you to return content that can be rendered into multiple content types, depending on the client request. -The `Response` class subclasses Django's `TemplateResponse`. `Response` objects are initialised with content, which should consist of native python primatives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content. +The `Response` class subclasses Django's `SimpleTemplateResponse`. `Response` objects are initialised with data, which should consist of native python primatives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content. -There's no requirement for you to use the `Response` class, you can also return regular `HttpResponse` objects from your views if you want, but it does provide a better interface for returning Web API responses. +There's no requirement for you to use the `Response` class, you can also return regular `HttpResponse` objects from your views if you want, but it provides a nicer interface for returning Web API responses. -## Response(content, headers=None, renderers=None, view=None, format=None, status=None) +Unless you want to heavily customize REST framework for some reason, you should always use an `APIView` class or `@api_view` function for views that return `Response` objects. Doing so ensures that the view can perform content negotiation and select the appropriate renderer for the response, before it is returned from the view. +## Response(data, status=None, headers=None) -## .renderers +Unlike regular `HttpResponse` objects, you do not instantiate `Response` objects with rendered content. Instead you pass in unrendered data, which may consist of any python primatives. -## .view +The renderers used by the `Response` class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primative datatypes before creating the `Response` object. -## .format +You can use REST framework's `Serializer` classes to perform this data serialization, or use your own custom serialization. +## .data + +The unrendered content of a `Request` object can be accessed using the `.data` attribute. + +## .content + +To access the rendered content of a `Response` object, you must first call `.render()`. You'll typically only need to do this in cases such as unit testing responses - when you return a `Response` from a view Django's response cycle will handle calling `.render()` for you. + +## .renderer + +When you return a `Response` instance, the `APIView` class or `@api_view` decorator will select the appropriate renderer, and set the `.renderer` attribute on the `Response`, before returning it from the view. [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/ \ No newline at end of file -- cgit v1.2.3 From b16fb5777168246b1e217640b818a82eb6e2141b Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 1 Oct 2012 15:49:19 +0100 Subject: Expand pagination support, add docs --- docs/api-guide/pagination.md | 98 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 docs/api-guide/pagination.md (limited to 'docs') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md new file mode 100644 index 00000000..0f0a32b5 --- /dev/null +++ b/docs/api-guide/pagination.md @@ -0,0 +1,98 @@ + + +# Pagination + +> Django provides a few classes that help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links. +> +> — [Django documentation][cite] + +REST framework includes a `PaginationSerializer` class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types. + +## Examples + +Let's start by taking a look at an example from the Django documentation. + + from django.core.paginator import Paginator + objects = ['john', 'paul', 'george', 'ringo'] + paginator = Paginator(objects, 2) + page = paginator.page(1) + page.object_list + # ['john', 'paul'] + +At this point we've got a page object. If we wanted to return this page object as a JSON response, we'd need to provide the client with context such as next and previous links, so that it would be able to page through the remaining results. + + from rest_framework.pagination import PaginationSerializer + serializer = PaginationSerializer(instance=page) + serializer.data + # {'count': 4, 'next': '?page=2', 'previous': None, 'results': [u'john', u'paul']} + +The `context` argument of the `PaginationSerializer` class may optionally include the request. If the request is included in the context then the next and previous links returned by the serializer will use absolute URLs instead of relative URLs. + + request = RequestFactory().get('/foobar') + serializer = PaginationSerializer(instance=page, context={'request': request}) + serializer.data + # {'count': 4, 'next': 'http://testserver/foobar?page=2', 'previous': None, 'results': [u'john', u'paul']} + +We could now return that data in a `Response` object, and it would be rendered into the correct media type. + +Our first example worked because we were using primative objects. If we wanted to paginate a queryset or other complex data, we'd need to specify a serializer to use to serialize the result set itself with. + +We can do this using the `object_serializer_class` attribute on the inner `Meta` class of the pagination serializer. For example. + + class UserSerializer(serializers.ModelSerializer): + """ + Serializes user querysets. + """ + class Meta: + model = User + fields = ('username', 'email') + + class PaginatedUserSerializer(pagination.PaginationSerializer): + """ + Serializes page objects of user querysets. + """ + class Meta: + object_serializer_class = UserSerializer + + queryset = User.objects.all() + paginator = Paginator(queryset, 20) + page = paginator.page(1) + serializer = PaginatedUserSerializer(instance=page) + serializer.data + # {'count': 1, 'next': None, 'previous': None, 'results': [{'username': u'admin', 'email': u'admin@example.com'}]} + +## Pagination in the generic views + +The generic class based views `ListAPIView` and `ListCreateAPIView` provide pagination of the returned querysets by default. You can customise this behaviour by altering the pagination style, by modifying the default number of results, or by turning pagination off completely. + +## Setting the default pagination style + +The default pagination style may be set globally, using the `PAGINATION_SERIALIZER` and `PAGINATE_BY` settings. For example. + + REST_FRAMEWORK = { + 'PAGINATION_SERIALIZER': ( + 'example_app.pagination.CustomPaginationSerializer', + ), + 'PAGINATE_BY': 10 + } + +You can also set the pagination style on a per-view basis, using the `ListAPIView` generic class-based view. + + class PaginatedListView(ListAPIView): + model = ExampleModel + pagination_serializer_class = CustomPaginationSerializer + paginate_by = 10 + +## Creating custom pagination serializers + +Override `pagination.BasePaginationSerializer`, and set the fields that you want the serializer to return. + +For example. + + class CustomPaginationSerializer(pagination.BasePaginationSerializer): + next = pagination.NextURLField() + total_results = serializers.Field(source='paginator.count') + + +[cite]: https://docs.djangoproject.com/en/dev/topics/pagination/ + -- cgit v1.2.3 From 8d1d99018725469061d5696a5552e7ebdb5cccc9 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 1 Oct 2012 16:17:01 +0100 Subject: Pagination docs --- docs/api-guide/pagination.md | 18 ++++++++++++------ docs/index.md | 2 ++ docs/static/css/default.css | 4 ++-- docs/template.html | 5 +++-- 4 files changed, 19 insertions(+), 10 deletions(-) (limited to 'docs') diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 0f0a32b5..6211a0ac 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -8,7 +8,7 @@ REST framework includes a `PaginationSerializer` class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types. -## Examples +## Paginating basic data Let's start by taking a look at an example from the Django documentation. @@ -35,6 +35,8 @@ The `context` argument of the `PaginationSerializer` class may optionally includ We could now return that data in a `Response` object, and it would be rendered into the correct media type. +## Paginating QuerySets + Our first example worked because we were using primative objects. If we wanted to paginate a queryset or other complex data, we'd need to specify a serializer to use to serialize the result set itself with. We can do this using the `object_serializer_class` attribute on the inner `Meta` class of the pagination serializer. For example. @@ -83,16 +85,20 @@ You can also set the pagination style on a per-view basis, using the `ListAPIVie pagination_serializer_class = CustomPaginationSerializer paginate_by = 10 +For more complex requirements such as serialization that differs depending on the requested media type you can override the `.get_paginate_by()` and `.get_pagination_serializer_class()` methods. + ## Creating custom pagination serializers -Override `pagination.BasePaginationSerializer`, and set the fields that you want the serializer to return. +To create a custom pagination serializer class you should override `pagination.BasePaginationSerializer` and set the fields that you want the serializer to return. + +For example, to nest a pair of links labelled 'prev' and 'next' you might use something like this. -For example. + class LinksSerializer(serializers.Serializer): + next = pagination.NextURLField(source='*') + prev = pagination.PreviousURLField(source='*') class CustomPaginationSerializer(pagination.BasePaginationSerializer): - next = pagination.NextURLField() + links = LinksSerializer(source='*') # Takes the page object as the source total_results = serializers.Field(source='paginator.count') - [cite]: https://docs.djangoproject.com/en/dev/topics/pagination/ - diff --git a/docs/index.md b/docs/index.md index e7db5dbc..92afbea8 100644 --- a/docs/index.md +++ b/docs/index.md @@ -85,6 +85,7 @@ The API guide is your complete reference manual to all the functionality provide * [Authentication][authentication] * [Permissions][permissions] * [Throttling][throttling] +* [Pagination][pagination] * [Content negotiation][contentnegotiation] * [Format suffixes][formatsuffixes] * [Returning URLs][reverse] @@ -161,6 +162,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [authentication]: api-guide/authentication.md [permissions]: api-guide/permissions.md [throttling]: api-guide/throttling.md +[pagination]: api-guide/pagination.md [contentnegotiation]: api-guide/content-negotiation.md [formatsuffixes]: api-guide/format-suffixes.md [reverse]: api-guide/reverse.md diff --git a/docs/static/css/default.css b/docs/static/css/default.css index 213a700e..49aac3a3 100644 --- a/docs/static/css/default.css +++ b/docs/static/css/default.css @@ -36,14 +36,14 @@ pre { } /* GitHub 'Star' badge */ -body.index #main-content iframe { +body.index-page #main-content iframe { float: right; margin-top: -12px; margin-right: -15px; } /* Travis CI badge */ -body.index #main-content p:first-of-type { +body.index-page #main-content p:first-of-type { float: right; margin-right: 8px; margin-top: -14px; diff --git a/docs/template.html b/docs/template.html index 4ac94f40..fbd30159 100644 --- a/docs/template.html +++ b/docs/template.html @@ -16,7 +16,7 @@ - +