From 49ecd157354b535694bb7aef9ad3bfefcf7d3950 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 4 Oct 2012 22:32:43 +0100 Subject: [PATCH] Latest docs build --- api-guide/fields.html | 165 +++++++++++++++++++ api-guide/generic-views.html | 39 ++++- api-guide/serializers.html | 3 + api-guide/settings.html | 5 +- index.html | 2 +- topics/formoverloading.html | 20 ++- tutorial/1-serialization.html | 6 +- tutorial/2-requests-and-responses.html | 4 +- tutorial/3-class-based-views.html | 12 +- tutorial/6-resource-orientated-projects.html | 6 +- 10 files changed, 229 insertions(+), 33 deletions(-) create mode 100644 api-guide/fields.html diff --git a/api-guide/fields.html b/api-guide/fields.html new file mode 100644 index 000000000..b43171c9d --- /dev/null +++ b/api-guide/fields.html @@ -0,0 +1,165 @@ + + + + Django REST framework + + + + + + + + + + + + + + + + +
+
+ + +
+

fields.py

+

Serializer fields

+
+

Flat is better than nested.

+

The Zen of Python

+
+

Generic Fields

+

Field

+

ModelField

+

Typed Fields

+

BooleanField

+

CharField

+

EmailField

+

DateField

+

DateTimeField

+

IntegerField

+

FloatField

+

Relational Fields

+

Relational fields are used to represent model relationships.

+

PrimaryKeyRelatedField

+

ManyPrimaryKeyRelatedField

+

HyperlinkedRelatedField

+

ManyHyperlinkedRelatedField

+
+
+
+ + + + + + + + + + diff --git a/api-guide/generic-views.html b/api-guide/generic-views.html index 4534f0596..4c8636e4a 100644 --- a/api-guide/generic-views.html +++ b/api-guide/generic-views.html @@ -95,7 +95,7 @@
@@ -126,12 +125,37 @@

Django Documentation

One of the key benefits of class based views is the way they allow you to compose bits of reusable behaviour. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.

-

Example

-

...

+

The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.

+

If the generic views don't suit the needs of your API, you can drop down to using the regular APIView class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.

+

Examples

+

Typically when using the generic views, you'll override the view, and set several class attributes.

+
class UserList(generics.ListCreateAPIView):
+    serializer = UserSerializer
+    model = User
+    permissions = (IsAdminUser,)
+    paginate_by = 100
+
+

For more complex cases you might also want to override various methods on the view class. For example.

+
class UserList(generics.ListCreateAPIView):
+    serializer = UserSerializer
+    model = User
+    permissions = (IsAdminUser,)
+
+    def get_paginate_by(self):
+        """
+        Use smaller pagination for HTML representations.
+        """
+        if self.request.accepted_media_type == 'text/html':
+            return 10
+        return 100
+
+

For very simple cases you might want to pass through any class attributes using the .as_view() method. For example, your URLconf might include something the following entry.

+
url(r'^/users/', ListCreateAPIView.as_view(model=User) name='user-list')
+

API Reference

ListAPIView

-

Used for read-write endpoints to represent a collection of model instances.

+

Used for read-only endpoints to represent a collection of model instances.

Provides a get method handler.

ListCreateAPIView

Used for read-write endpoints to represent a collection of model instances.

@@ -144,6 +168,7 @@

Provides get, put and delete method handlers.


Base views

+

Each of the generic views provided is built by combining one of the base views below, with one or more mixin classes.

BaseAPIView

Extends REST framework's APIView class, adding support for serialization of model instances and model querysets.

MultipleObjectBaseAPIView

@@ -154,7 +179,7 @@

See also: ccbv.co.uk documentation for SingleObjectMixin.


Mixins

-

The mixin classes provide the actions that are used

+

The mixin classes provide the actions that are used to provide the basic view behaviour. Note that the mixin classes provide action methods rather than defining the handler methods such as .get() and .post() directly. This allows for more flexible composition of behaviour.

ListModelMixin

Provides a .list(request, *args, **kwargs) method, that implements listing a queryset.

CreateModelMixin

@@ -165,8 +190,6 @@

Provides a .update(request, *args, **kwargs) method, that implements updating and saving an existing model instance.

DestroyModelMixin

Provides a .destroy(request, *args, **kwargs) method, that implements deletion of an existing model instance.

-

MetadataMixin

-

Provides a .metadata(request, *args, **kwargs) method, that returns a response containing metadata about the view.

diff --git a/api-guide/serializers.html b/api-guide/serializers.html index 96e0c5a52..ba45269c1 100644 --- a/api-guide/serializers.html +++ b/api-guide/serializers.html @@ -291,6 +291,9 @@ The ModelSerializer class lets you automatically create a Serialize class Meta: model = Account + def get_pk_field(self, model_field): + return Field(readonly=True) + def get_nested_field(self, model_field): return ModelSerializer() diff --git a/api-guide/settings.html b/api-guide/settings.html index dda3523d8..77e7ad60f 100644 --- a/api-guide/settings.html +++ b/api-guide/settings.html @@ -110,6 +110,7 @@
  • FORM_CONTENT_OVERRIDE
  • FORM_CONTENTTYPE_OVERRIDE
  • URL_ACCEPT_OVERRIDE
  • +
  • URL_FORMAT_OVERRIDE
  • @@ -202,7 +203,9 @@ print api_settings.DEFAULT_AUTHENTICATION

    URL_ACCEPT_OVERRIDE

    The name of a URL parameter that may be used to override the HTTP Accept header.

    If the value of this setting is None then URL accept overloading will be disabled.

    -

    Default: '_accept'

    +

    Default: 'accept'

    +

    URL_FORMAT_OVERRIDE

    +

    Default: 'format'

    diff --git a/index.html b/index.html index dba8081ed..4242aa6f3 100644 --- a/index.html +++ b/index.html @@ -111,7 +111,7 @@
    -

    Build Status

    +

    ![travis-build-image]

    Django REST framework

    A toolkit for building well-connected, self-describing Web APIs.

    WARNING: This documentation is for the 2.0 redesign of REST framework. It is a work in progress.

    diff --git a/topics/formoverloading.html b/topics/formoverloading.html index 31b8a68ff..4975ee89e 100644 --- a/topics/formoverloading.html +++ b/topics/formoverloading.html @@ -94,9 +94,11 @@
    -

    Browser based PUT & DELETE

    +

    Browser hacks

    "There are two noncontroversial uses for overloaded POST. The first is to simulate HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE"

    RESTful Web Services, Leonard Richardson & Sam Ruby.

    -

    Overloading the HTTP method

    +

    Browser based PUT, DELETE, etc...

    TODO: Preamble. Note that this is the same strategy as is used in Ruby on Rails.

    For example, given the following form:

    <form action="/news-items/5" method="POST">
    @@ -117,7 +119,7 @@
     </form>
     

    request.method would return "DELETE".

    -

    Overloading the HTTP content type

    +

    Browser based submission of non-form content

    Browser-based submission of content types other than form are supported by using form fields named _content and _content_type:

    For example, given the following form:

    <form action="/news-items/5" method="PUT">
    @@ -126,10 +128,10 @@
     </form>
     

    request.content_type would return "application/json", and request.content would return "{'count': 1}"

    -

    Why not just use Javascript?

    -

    [TODO]

    +

    URL based accept headers

    +

    URL based format suffixes

    Doesn't HTML5 support PUT and DELETE forms?

    -

    Nope. It was at one point intended to support PUT and DELETE forms, but was later dropped from the spec. There remains ongoing discussion about adding support for PUT and DELETE, as well as how to support content-types other than form-encoded data.

    +

    Nope. It was at one point intended to support PUT and DELETE forms, but was later dropped from the spec. There remains ongoing discussion about adding support for PUT and DELETE, as well as how to support content types other than form-encoded data.

    diff --git a/tutorial/1-serialization.html b/tutorial/1-serialization.html index d4178070c..9fda915a5 100644 --- a/tutorial/1-serialization.html +++ b/tutorial/1-serialization.html @@ -172,7 +172,7 @@ class Comment(models.Model):
    python manage.py syncdb
     

    Creating a Serializer class

    -

    We're going to create a simple Web API that we can use to edit these comment objects with. The first thing we need is a way of serializing and deserializing the objects into representations such as json. We do this by declaring serializers, that work very similarly to Django's forms. Create a file in the project named serializers.py and add the following.

    +

    We're going to create a simple Web API that we can use to edit these comment objects with. The first thing we need is a way of serializing and deserializing the objects into representations such as json. We do this by declaring serializers that work very similarly to Django's forms. Create a file in the project named serializers.py and add the following.

    from blog import models
     from rest_framework import serializers
     
    @@ -277,7 +277,7 @@ def comment_root(request):
                 return JSONResponse(serializer.errors, status=400)
     

    Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as csrf_exempt. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.

    -

    We'll also need a view which corrosponds to an individual comment, and can be used to retrieve, update or delete the comment.

    +

    We'll also need a view which corresponds to an individual comment, and can be used to retrieve, update or delete the comment.

    @csrf_exempt
     def comment_instance(request, pk):
         """
    @@ -306,7 +306,7 @@ def comment_instance(request, pk):
             comment.delete()
             return HttpResponse(status=204)
     
    -

    Finally we need to wire these views up, in the tutorial/urls.py file.

    +

    Finally we need to wire these views up. Create the blog/urls.py file:

    from django.conf.urls import patterns, url
     
     urlpatterns = patterns('blog.views',
    diff --git a/tutorial/2-requests-and-responses.html b/tutorial/2-requests-and-responses.html
    index e98f8d807..d98a33cd8 100644
    --- a/tutorial/2-requests-and-responses.html
    +++ b/tutorial/2-requests-and-responses.html
    @@ -129,7 +129,7 @@ request.DATA  # Handles arbitrary data.  Works any HTTP request with content.
     
  • The @api_view decorator for working with function based views.
  • The APIView class for working with class based views.
  • -

    These wrappers provide a few bits of functionality such as making sure you recieve Request instances in your view, and adding context to Response objects so that content negotiation can be performed.

    +

    These wrappers provide a few bits of functionality such as making sure you receive Request instances in your view, and adding context to Response objects so that content negotiation can be performed.

    The wrappers also provide behaviour such as returning 405 Method Not Allowed responses when appropriate, and handling any ParseError exception that occurs when accessing request.DATA with malformed input.

    Pulling it all together

    Okay, let's go ahead and start using these new components to write a few views.

    @@ -208,7 +208,7 @@ urlpatterns = patterns('blogpost.views', urlpatterns = format_suffix_patterns(urlpatterns)
    -

    We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of refering to a specific format.

    +

    We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format.

    How's it looking?

    Go ahead and test the API from the command line, as we did in tutorial part 1. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.

    TODO: Describe using accept headers, content-type headers, and format suffixed URLs

    diff --git a/tutorial/3-class-based-views.html b/tutorial/3-class-based-views.html index 67aa9fce1..18dfac74c 100644 --- a/tutorial/3-class-based-views.html +++ b/tutorial/3-class-based-views.html @@ -129,10 +129,10 @@ class CommentRoot(APIView): if serializer.is_valid(): comment = serializer.object comment.save() - return Response(serializer.serialized, status=status.HTTP_201_CREATED) - return Response(serializer.serialized_errors, status=status.HTTP_400_BAD_REQUEST) + return Response(serializer.data, status=status.HTTP_201_CREATED) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -

    So far, so good. It looks pretty similar to the previous case, but we've got better seperation between the different HTTP methods. We'll also need to update the instance view.

    +

    So far, so good. It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods. We'll also need to update the instance view.

    class CommentInstance(APIView):
         """
         Retrieve, update or delete a comment instance.
    @@ -223,15 +223,15 @@ class CommentRoot(mixins.ListModelMixin,
     from blog.serializers import CommentSerializer
     from rest_framework import generics
     
    -class CommentRoot(generics.RootAPIView):
    +class CommentRoot(generics.ListCreateAPIView):
         model = Comment
         serializer_class = CommentSerializer
     
    -class CommentInstance(generics.InstanceAPIView):
    +class CommentInstance(generics.RetrieveUpdateDestroyAPIView):
         model = Comment
         serializer_class = CommentSerializer
     
    -

    Wow, that's pretty concise. We've got a huge amount for free, and our code looks like good, clean, idomatic Django.

    +

    Wow, that's pretty concise. We've got a huge amount for free, and our code looks like good, clean, idiomatic Django.

    Next we'll move onto part 4 of the tutorial, where we'll take a look at how we can customize the behavior of our views to support a range of authentication, permissions, throttling and other aspects.

    diff --git a/tutorial/6-resource-orientated-projects.html b/tutorial/6-resource-orientated-projects.html index 0bec7aafb..2ec5f16bd 100644 --- a/tutorial/6-resource-orientated-projects.html +++ b/tutorial/6-resource-orientated-projects.html @@ -110,8 +110,8 @@

    Resource classes are just View classes that don't have any handler methods bound to them. The actions on a resource are defined,

    This allows us to:

    Refactoring to use Resources, not Views

    For instance, we can re-write our 4 sets of views into something more compact...

    @@ -158,7 +158,7 @@ router.register(resources.CommentResource) urlpatterns = router.urlpatterns

    Trade-offs between views vs resources.

    -

    Writing resource-orientated code can be a good thing. It helps ensure that URL conventions will be consistent across your APIs, and minimises the amount of code you need to write.

    +

    Writing resource-oriented code can be a good thing. It helps ensure that URL conventions will be consistent across your APIs, and minimises the amount of code you need to write.

    The trade-off is that the behaviour is less explict. It can be more difficult to determine what code path is being followed, or where to override some behaviour.

    Onwards and upwards.

    We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here's a few places you can start: