django-rest-framework/tutorial/3-class-based-views.html
2012-09-05 13:05:36 +01:00

275 lines
13 KiB
HTML

<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Django REST framework</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="http://tomchristie.github.com/django-rest-framework/css/bootstrap.css" rel="stylesheet">
<style type="text/css">
body {
padding-top: 60px;
padding-bottom: 40px;
}
.sidebar-nav {
padding: 9px 0;
}
.nav-list li.main {
font-weight: bold;
}
blockquote {
font-family: Georgia, serif;
font-size: 18px;
font-style: italic;
margin: 0.25em 0;
padding: 0.25em 40px;
line-height: 1.45;
position: relative;
color: #383838;
border-left: none;
}
blockquote:before {
display: block;
content: "\201C";
font-size: 80px;
position: absolute;
left: -10px;
top: -20px;
color: #7a7a7a;
}
blockquote p:last-child {
color: #999999;
font-size: 14px;
display: block;
margin-top: 5px;
}
</style>
<link href="http://tomchristie.github.com/django-rest-framework/css/bootstrap-responsive.css" rel="stylesheet">
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container-fluid">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="http://tomchristie.github.com/django-rest-framework">Django REST framework</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li><a href="http://tomchristie.github.com/django-rest-framework">Home</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/1-serialization">1 - Serialization</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/2-requests-and-responses">2 - Requests and responses</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/3-class-based-views">3 - Class based views</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/4-authentication-permissions-and-throttling">4 - Authentication, permissions and throttling</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/6-resource-orientated-projects">6 - Resource orientated projects</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/requests">Requests</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/responses">Responses</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/views">Views</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/parsers">Parsers</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/renderers">Renderers</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/serializers">Serializers</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/fields">Serializer fields</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/authentication">Authentication</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/permissions">Permissions</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/throttling">Throttling</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/exceptions">Exceptions</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/status-codes">Status codes</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/reverse">Returning URLs</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/settings">Settings</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Topics <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/csrf">Working with AJAX and CSRF</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/formoverloading">Browser based PUT, PATCH and DELETE</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/contributing">Contributing to REST framework</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/credits">Credits</a></li>
</ul>
</li>
</ul>
<ul class="nav pull-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Trunk</a></li>
<li><a href="#">2.0.0</a></li>
</ul>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container-fluid">
<div class="row-fluid">
<div class="span3">
<div class="well affix span3">
<ul class="nav nav-list side-nav">
<li class="main"><a href="#tutorial-3-using-class-based-views">Tutorial 3: Using Class Based Views</a></li>
<li><a href="#rewriting-our-api-using-class-based-views">Rewriting our API using class based views</a></li>
<li><a href="#using-mixins">Using mixins</a></li>
<li><a href="#reusing-generic-class-based-views">Reusing generic class based views</a></li>
</ul>
</div>
</div>
<div class="span9">
<h1 id="tutorial-3-using-class-based-views">Tutorial 3: Using Class Based Views</h1>
<p>We can also write our API views using class based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a>.</p>
<h2 id="rewriting-our-api-using-class-based-views">Rewriting our API using class based views</h2>
<p>We'll start by rewriting the root view as a class based view. All this involves is a little bit of refactoring.</p>
<pre><code>from blog.models import Comment
from blog.serializers import ComentSerializer
from django.http import Http404
from djangorestframework.views import APIView
from djangorestframework.response import Response
from djangorestframework.status import status
class CommentRoot(APIView):
"""
List all comments, or create a new comment.
"""
def get(self, request, format=None):
comments = Comment.objects.all()
serializer = ComentSerializer(instance=comments)
return Response(serializer.data)
def post(self, request, format=None)
serializer = ComentSerializer(request.DATA)
if serializer.is_valid():
comment = serializer.object
comment.save()
return Response(serializer.serialized, status=HTTP_201_CREATED)
return Response(serializer.serialized_errors, status=HTTP_400_BAD_REQUEST)
comment_root = CommentRoot.as_view()
</code></pre>
<p>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. </p>
<pre><code>class CommentInstance(APIView):
"""
Retrieve, update or delete a comment instance.
"""
def get_object(self, pk):
try:
return Comment.objects.get(pk=pk)
except Comment.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
comment = self.get_object(pk)
serializer = CommentSerializer(instance=comment)
return Response(serializer.data)
def put(self, request, pk, format=None):
comment = self.get_object(pk)
serializer = CommentSerializer(request.DATA, instance=comment)
if serializer.is_valid():
comment = serializer.deserialized
comment.save()
return Response(serializer.data)
return Response(serializer.error_data, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
comment = self.get_object(pk)
comment.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
comment_instance = CommentInstance.as_view()
</code></pre>
<p>That's looking good. Again, it's still pretty similar to the function based view right now.
Okay, we're done. If you run the development server everything should be working just as before.</p>
<h2 id="using-mixins">Using mixins</h2>
<p>One of the big wins of using class based views is that it allows us to easily compose reusable bits of behaviour.</p>
<p>The create/retrieve/update/delete operations that we've been using so far is going to be pretty simliar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes.</p>
<p>We can compose those mixin classes, to recreate our existing API behaviour with less code.</p>
<pre><code>from blog.models import Comment
from blog.serializers import CommentSerializer
from djangorestframework import mixins
from djangorestframework import views
class CommentRoot(mixins.ListModelMixin,
mixins.CreateModelMixin,
views.MultipleObjectBaseView):
model = Comment
serializer_class = CommentSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
class CommentInstance(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
views.SingleObjectBaseView):
model = Comment
serializer_class = CommentSerializer
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
</code></pre>
<h2 id="reusing-generic-class-based-views">Reusing generic class based views</h2>
<p>That's a lot less code than before, but we can go one step further still. REST framework also provides a set of already mixed-in views.</p>
<pre><code>from blog.models import Comment
from blog.serializers import CommentSerializer
from djangorestframework import views
class CommentRoot(views.RootModelView):
model = Comment
serializer_class = CommentSerializer
class CommentInstance(views.InstanceModelView):
model = Comment
serializer_class = CommentSerializer
</code></pre>
<p>Wow, that's pretty concise. We've got a huge amount for free, and our code looks like
good, clean, idomatic Django.</p>
<p>Next we'll move onto <a href="4-authentication-permissions-and-throttling.html">part 4 of the tutorial</a>, 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.</p>
</div><!--/span-->
</div><!--/row-->
</div><!--/.fluid-container-->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="http://tomchristie.github.com/django-rest-framework/js/jquery.js"></script>
<script src="http://tomchristie.github.com/django-rest-framework/js/bootstrap-dropdown.js"></script>
<script src="http://tomchristie.github.com/django-rest-framework/js/bootstrap-scrollspy.js"></script>
<script>
//$('.side-nav').scrollspy()
var shiftWindow = function() { scrollBy(0, -50) };
if (location.hash) shiftWindow();
window.addEventListener("hashchange", shiftWindow);
</script>
</body></html>