django-rest-framework/api-guide/views/index.html
2019-07-17 14:11:16 +00:00

668 lines
30 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Views - Django REST framework</title>
<link href="../../img/favicon.ico" rel="icon" type="image/x-icon">
<link rel="canonical" href="https://www.django-rest-framework.org/api-guide/views/" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Django, API, REST, Views">
<meta name="author" content="Tom Christie">
<!-- Le styles -->
<link href="../../css/prettify.css" rel="stylesheet">
<link href="../../css/bootstrap.css" rel="stylesheet">
<link href="../../css/bootstrap-responsive.css" rel="stylesheet">
<link href="../../css/default.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]-->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-18852272-2']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
<style>
#sidebarInclude img {
margin-bottom: 10px;
}
#sidebarInclude a.promo {
color: black;
}
@media (max-width: 767px) {
div.promo {
display: none;
}
}
</style>
</head>
<body onload="prettyPrint()" class="-page">
<div class="wrapper">
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container-fluid">
<a class="repo-link btn btn-primary btn-small" href="https://github.com/encode/django-rest-framework/tree/master">GitHub</a>
<a class="repo-link btn btn-inverse btn-small " rel="next" href="../generic-views/">
Next <i class="icon-arrow-right icon-white"></i>
</a>
<a class="repo-link btn btn-inverse btn-small " rel="prev" href="../responses/">
<i class="icon-arrow-left icon-white"></i> Previous
</a>
<a id="search_modal_show" class="repo-link btn btn-inverse btn-small" href="#mkdocs_search_modal" data-toggle="modal" data-target="#mkdocs_search_modal"><i class="icon-search icon-white"></i> Search</a>
<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="https://www.django-rest-framework.org/">Django REST framework</a>
<div class="nav-collapse collapse">
<!-- Main navigation -->
<ul class="nav navbar-nav">
<li >
<a href="../..">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="../../tutorial/quickstart/">Quickstart</a>
</li>
<li >
<a href="../../tutorial/1-serialization/">1 - Serialization</a>
</li>
<li >
<a href="../../tutorial/2-requests-and-responses/">2 - Requests and responses</a>
</li>
<li >
<a href="../../tutorial/3-class-based-views/">3 - Class based views</a>
</li>
<li >
<a href="../../tutorial/4-authentication-and-permissions/">4 - Authentication and permissions</a>
</li>
<li >
<a href="../../tutorial/5-relationships-and-hyperlinked-apis/">5 - Relationships and hyperlinked APIs</a>
</li>
<li >
<a href="../../tutorial/6-viewsets-and-routers/">6 - Viewsets and routers</a>
</li>
</ul>
</li>
<li class="dropdown active">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
<ul class="dropdown-menu">
<li >
<a href="../requests/">Requests</a>
</li>
<li >
<a href="../responses/">Responses</a>
</li>
<li class="active" >
<a href="./">Views</a>
</li>
<li >
<a href="../generic-views/">Generic views</a>
</li>
<li >
<a href="../viewsets/">Viewsets</a>
</li>
<li >
<a href="../routers/">Routers</a>
</li>
<li >
<a href="../parsers/">Parsers</a>
</li>
<li >
<a href="../renderers/">Renderers</a>
</li>
<li >
<a href="../serializers/">Serializers</a>
</li>
<li >
<a href="../fields/">Serializer fields</a>
</li>
<li >
<a href="../relations/">Serializer relations</a>
</li>
<li >
<a href="../validators/">Validators</a>
</li>
<li >
<a href="../authentication/">Authentication</a>
</li>
<li >
<a href="../permissions/">Permissions</a>
</li>
<li >
<a href="../caching/">Caching</a>
</li>
<li >
<a href="../throttling/">Throttling</a>
</li>
<li >
<a href="../filtering/">Filtering</a>
</li>
<li >
<a href="../pagination/">Pagination</a>
</li>
<li >
<a href="../versioning/">Versioning</a>
</li>
<li >
<a href="../content-negotiation/">Content negotiation</a>
</li>
<li >
<a href="../metadata/">Metadata</a>
</li>
<li >
<a href="../schemas/">Schemas</a>
</li>
<li >
<a href="../format-suffixes/">Format suffixes</a>
</li>
<li >
<a href="../reverse/">Returning URLs</a>
</li>
<li >
<a href="../exceptions/">Exceptions</a>
</li>
<li >
<a href="../status-codes/">Status codes</a>
</li>
<li >
<a href="../testing/">Testing</a>
</li>
<li >
<a href="../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="../../topics/documenting-your-api/">Documenting your API</a>
</li>
<li >
<a href="../../topics/api-clients/">API Clients</a>
</li>
<li >
<a href="../../topics/internationalization/">Internationalization</a>
</li>
<li >
<a href="../../topics/ajax-csrf-cors/">AJAX, CSRF & CORS</a>
</li>
<li >
<a href="../../topics/html-and-forms/">HTML & Forms</a>
</li>
<li >
<a href="../../topics/browser-enhancements/">Browser Enhancements</a>
</li>
<li >
<a href="../../topics/browsable-api/">The Browsable API</a>
</li>
<li >
<a href="../../topics/rest-hypermedia-hateoas/">REST, Hypermedia & HATEOAS</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Community <b class="caret"></b></a>
<ul class="dropdown-menu">
<li >
<a href="../../community/tutorials-and-resources/">Tutorials and Resources</a>
</li>
<li >
<a href="../../community/third-party-packages/">Third Party Packages</a>
</li>
<li >
<a href="../../community/contributing/">Contributing to REST framework</a>
</li>
<li >
<a href="../../community/project-management/">Project management</a>
</li>
<li >
<a href="../../community/release-notes/">Release Notes</a>
</li>
<li >
<a href="../../community/3.10-announcement/">3.10 Announcement</a>
</li>
<li >
<a href="../../community/3.9-announcement/">3.9 Announcement</a>
</li>
<li >
<a href="../../community/3.8-announcement/">3.8 Announcement</a>
</li>
<li >
<a href="../../community/3.7-announcement/">3.7 Announcement</a>
</li>
<li >
<a href="../../community/3.6-announcement/">3.6 Announcement</a>
</li>
<li >
<a href="../../community/3.5-announcement/">3.5 Announcement</a>
</li>
<li >
<a href="../../community/3.4-announcement/">3.4 Announcement</a>
</li>
<li >
<a href="../../community/3.3-announcement/">3.3 Announcement</a>
</li>
<li >
<a href="../../community/3.2-announcement/">3.2 Announcement</a>
</li>
<li >
<a href="../../community/3.1-announcement/">3.1 Announcement</a>
</li>
<li >
<a href="../../community/3.0-announcement/">3.0 Announcement</a>
</li>
<li >
<a href="../../community/kickstarter-announcement/">Kickstarter Announcement</a>
</li>
<li >
<a href="../../community/mozilla-grant/">Mozilla Grant</a>
</li>
<li >
<a href="../../community/funding/">Funding</a>
</li>
<li >
<a href="../../community/jobs/">Jobs</a>
</li>
</ul>
</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</div>
</div>
<div class="body-content">
<div class="container-fluid">
<!-- Search Modal -->
<div id="mkdocs_search_modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h3 id="myModalLabel">Documentation search</h3>
</div>
<div class="modal-body">
<form role="form" autocomplete="off">
<div class="form-group">
<input type="text" name="q" class="form-control" placeholder="Search..." id="mkdocs-search-query">
</div>
</form>
<div id="mkdocs-search-results"></div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>
<div class="row-fluid">
<div class="span3">
<div id="table-of-contents">
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
<li class="main">
<a href="#class-based-views">Class-based Views</a>
</li>
<li>
<a href="#api-policy-attributes">API policy attributes</a>
</li>
<li>
<a href="#api-policy-instantiation-methods">API policy instantiation methods</a>
</li>
<li>
<a href="#api-policy-implementation-methods">API policy implementation methods</a>
</li>
<li>
<a href="#dispatch-methods">Dispatch methods</a>
</li>
<li class="main">
<a href="#function-based-views">Function Based Views</a>
</li>
<li>
<a href="#api_view">@api_view()</a>
</li>
<li>
<a href="#api-policy-decorators">API policy decorators</a>
</li>
<li>
<a href="#view-schema-decorator">View schema decorator</a>
</li>
<div class="promo">
<hr/>
<div id="sidebarInclude">
</div>
</ul>
</div>
</div>
<div id="main-content" class="span9">
<a class="github" href="https://github.com/encode/django-rest-framework/tree/master/rest_framework/decorators.py">
<span class="label label-info">decorators.py</span>
</a>
<a class="github" href="https://github.com/encode/django-rest-framework/tree/master/rest_framework/views.py">
<span class="label label-info">views.py</span>
</a>
<h1 id="class-based-views"><a class="toclink" href="#class-based-views">Class-based Views</a></h1>
<blockquote>
<p>Django's class-based views are a welcome departure from the old-style views.</p>
<p>&mdash; <a href="https://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html">Reinout van Rees</a></p>
</blockquote>
<p>REST framework provides an <code>APIView</code> class, which subclasses Django's <code>View</code> class.</p>
<p><code>APIView</code> classes are different from regular <code>View</code> classes in the following ways:</p>
<ul>
<li>Requests passed to the handler methods will be REST framework's <code>Request</code> instances, not Django's <code>HttpRequest</code> instances.</li>
<li>Handler methods may return REST framework's <code>Response</code>, instead of Django's <code>HttpResponse</code>. The view will manage content negotiation and setting the correct renderer on the response.</li>
<li>Any <code>APIException</code> exceptions will be caught and mediated into appropriate responses.</li>
<li>Incoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method.</li>
</ul>
<p>Using the <code>APIView</code> class is pretty much the same as using a regular <code>View</code> class, as usual, the incoming request is dispatched to an appropriate handler method such as <code>.get()</code> or <code>.post()</code>. Additionally, a number of attributes may be set on the class that control various aspects of the API policy.</p>
<p>For example:</p>
<pre><code>from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
from django.contrib.auth.models import User
class ListUsers(APIView):
"""
View to list all users in the system.
* Requires token authentication.
* Only admin users are able to access this view.
"""
authentication_classes = [authentication.TokenAuthentication]
permission_classes = [permissions.IsAdminUser]
def get(self, request, format=None):
"""
Return a list of all users.
"""
usernames = [user.username for user in User.objects.all()]
return Response(usernames)
</code></pre>
<hr />
<p><strong>Note</strong>: The full methods, attributes on, and relations between Django REST Framework's <code>APIView</code>, <code>GenericAPIView</code>, various <code>Mixins</code>, and <code>Viewsets</code> can be initially complex. In addition to the documentation here, the <a href="http://www.cdrf.co">Classy Django REST Framework</a> resource provides a browsable reference, with full methods and attributes, for each of Django REST Framework's class-based views.</p>
<hr />
<h2 id="api-policy-attributes"><a class="toclink" href="#api-policy-attributes">API policy attributes</a></h2>
<p>The following attributes control the pluggable aspects of API views.</p>
<h3 id="renderer_classes"><a class="toclink" href="#renderer_classes">.renderer_classes</a></h3>
<h3 id="parser_classes"><a class="toclink" href="#parser_classes">.parser_classes</a></h3>
<h3 id="authentication_classes"><a class="toclink" href="#authentication_classes">.authentication_classes</a></h3>
<h3 id="throttle_classes"><a class="toclink" href="#throttle_classes">.throttle_classes</a></h3>
<h3 id="permission_classes"><a class="toclink" href="#permission_classes">.permission_classes</a></h3>
<h3 id="content_negotiation_class"><a class="toclink" href="#content_negotiation_class">.content_negotiation_class</a></h3>
<h2 id="api-policy-instantiation-methods"><a class="toclink" href="#api-policy-instantiation-methods">API policy instantiation methods</a></h2>
<p>The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods.</p>
<h3 id="get_renderersself"><a class="toclink" href="#get_renderersself">.get_renderers(self)</a></h3>
<h3 id="get_parsersself"><a class="toclink" href="#get_parsersself">.get_parsers(self)</a></h3>
<h3 id="get_authenticatorsself"><a class="toclink" href="#get_authenticatorsself">.get_authenticators(self)</a></h3>
<h3 id="get_throttlesself"><a class="toclink" href="#get_throttlesself">.get_throttles(self)</a></h3>
<h3 id="get_permissionsself"><a class="toclink" href="#get_permissionsself">.get_permissions(self)</a></h3>
<h3 id="get_content_negotiatorself"><a class="toclink" href="#get_content_negotiatorself">.get_content_negotiator(self)</a></h3>
<h3 id="get_exception_handlerself"><a class="toclink" href="#get_exception_handlerself">.get_exception_handler(self)</a></h3>
<h2 id="api-policy-implementation-methods"><a class="toclink" href="#api-policy-implementation-methods">API policy implementation methods</a></h2>
<p>The following methods are called before dispatching to the handler method.</p>
<h3 id="check_permissionsself-request"><a class="toclink" href="#check_permissionsself-request">.check_permissions(self, request)</a></h3>
<h3 id="check_throttlesself-request"><a class="toclink" href="#check_throttlesself-request">.check_throttles(self, request)</a></h3>
<h3 id="perform_content_negotiationself-request-forcefalse"><a class="toclink" href="#perform_content_negotiationself-request-forcefalse">.perform_content_negotiation(self, request, force=False)</a></h3>
<h2 id="dispatch-methods"><a class="toclink" href="#dispatch-methods">Dispatch methods</a></h2>
<p>The following methods are called directly by the view's <code>.dispatch()</code> method.
These perform any actions that need to occur before or after calling the handler methods such as <code>.get()</code>, <code>.post()</code>, <code>put()</code>, <code>patch()</code> and <code>.delete()</code>.</p>
<h3 id="initialself-request-42args-kwargs"><a class="toclink" href="#initialself-request-42args-kwargs">.initial(self, request, *args, **kwargs)</a></h3>
<p>Performs any actions that need to occur before the handler method gets called.
This method is used to enforce permissions and throttling, and perform content negotiation.</p>
<p>You won't typically need to override this method.</p>
<h3 id="handle_exceptionself-exc"><a class="toclink" href="#handle_exceptionself-exc">.handle_exception(self, exc)</a></h3>
<p>Any exception thrown by the handler method will be passed to this method, which either returns a <code>Response</code> instance, or re-raises the exception.</p>
<p>The default implementation handles any subclass of <code>rest_framework.exceptions.APIException</code>, as well as Django's <code>Http404</code> and <code>PermissionDenied</code> exceptions, and returns an appropriate error response.</p>
<p>If you need to customize the error responses your API returns you should subclass this method.</p>
<h3 id="initialize_requestself-request-42args-kwargs"><a class="toclink" href="#initialize_requestself-request-42args-kwargs">.initialize_request(self, request, *args, **kwargs)</a></h3>
<p>Ensures that the request object that is passed to the handler method is an instance of <code>Request</code>, rather than the usual Django <code>HttpRequest</code>.</p>
<p>You won't typically need to override this method.</p>
<h3 id="finalize_responseself-request-response-42args-kwargs"><a class="toclink" href="#finalize_responseself-request-response-42args-kwargs">.finalize_response(self, request, response, *args, **kwargs)</a></h3>
<p>Ensures that any <code>Response</code> object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation.</p>
<p>You won't typically need to override this method.</p>
<hr />
<h1 id="function-based-views"><a class="toclink" href="#function-based-views">Function Based Views</a></h1>
<blockquote>
<p>Saying [that class-based views] is always the superior solution is a mistake.</p>
<p>&mdash; <a href="http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html">Nick Coghlan</a></p>
</blockquote>
<p>REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of <code>Request</code> (rather than the usual Django <code>HttpRequest</code>) and allows them to return a <code>Response</code> (instead of a Django <code>HttpResponse</code>), and allow you to configure how the request is processed.</p>
<h2 id="api_view"><a class="toclink" href="#api_view">@api_view()</a></h2>
<p><strong>Signature:</strong> <code>@api_view(http_method_names=['GET'])</code></p>
<p>The core of this functionality is the <code>api_view</code> decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:</p>
<pre><code>from rest_framework.decorators import api_view
@api_view()
def hello_world(request):
return Response({"message": "Hello, world!"})
</code></pre>
<p>This view will use the default renderers, parsers, authentication classes etc specified in the <a href="../settings/">settings</a>.</p>
<p>By default only <code>GET</code> methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behaviour, specify which methods the view allows, like so:</p>
<pre><code>@api_view(['GET', 'POST'])
def hello_world(request):
if request.method == 'POST':
return Response({"message": "Got some data!", "data": request.data})
return Response({"message": "Hello, world!"})
</code></pre>
<h2 id="api-policy-decorators"><a class="toclink" href="#api-policy-decorators">API policy decorators</a></h2>
<p>To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come <em>after</em> (below) the <code>@api_view</code> decorator. For example, to create a view that uses a <a href="../throttling/">throttle</a> to ensure it can only be called once per day by a particular user, use the <code>@throttle_classes</code> decorator, passing a list of throttle classes:</p>
<pre><code>from rest_framework.decorators import api_view, throttle_classes
from rest_framework.throttling import UserRateThrottle
class OncePerDayUserThrottle(UserRateThrottle):
rate = '1/day'
@api_view(['GET'])
@throttle_classes([OncePerDayUserThrottle])
def view(request):
return Response({"message": "Hello for today! See you tomorrow!"})
</code></pre>
<p>These decorators correspond to the attributes set on <code>APIView</code> subclasses, described above.</p>
<p>The available decorators are:</p>
<ul>
<li><code>@renderer_classes(...)</code></li>
<li><code>@parser_classes(...)</code></li>
<li><code>@authentication_classes(...)</code></li>
<li><code>@throttle_classes(...)</code></li>
<li><code>@permission_classes(...)</code></li>
</ul>
<p>Each of these decorators takes a single argument which must be a list or tuple of classes.</p>
<h2 id="view-schema-decorator"><a class="toclink" href="#view-schema-decorator">View schema decorator</a></h2>
<p>To override the default schema generation for function based views you may use
the <code>@schema</code> decorator. This must come <em>after</em> (below) the <code>@api_view</code>
decorator. For example:</p>
<pre><code>from rest_framework.decorators import api_view, schema
from rest_framework.schemas import AutoSchema
class CustomAutoSchema(AutoSchema):
def get_link(self, path, method, base_url):
# override view introspection here...
@api_view(['GET'])
@schema(CustomAutoSchema())
def view(request):
return Response({"message": "Hello for today! See you tomorrow!"})
</code></pre>
<p>This decorator takes a single <code>AutoSchema</code> instance, an <code>AutoSchema</code> subclass
instance or <code>ManualSchema</code> instance as described in the <a href="../schemas/">Schemas documentation</a>.
You may pass <code>None</code> in order to exclude the view from schema generation.</p>
<pre><code>@api_view(['GET'])
@schema(None)
def view(request):
return Response({"message": "Will not appear in schema!"})
</code></pre>
</div> <!--/span-->
</div> <!--/row-->
</div> <!--/.fluid-container-->
</div> <!--/.body content-->
<div id="push"></div>
</div> <!--/.wrapper -->
<footer class="span12">
<p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.
</p>
</footer>
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script async src="https://fund.django-rest-framework.org/sidebar_include.js"></script>
<script src="../../js/jquery-1.8.1-min.js"></script>
<script src="../../js/prettify-1.0.js"></script>
<script src="../../js/bootstrap-2.1.1-min.js"></script>
<script src="../../js/theme.js"></script>
<script>var base_url = '../..';</script>
<script src="../../search/main.js" defer></script>
<script>
var shiftWindow = function() {
scrollBy(0, -50)
};
if (location.hash) shiftWindow();
window.addEventListener("hashchange", shiftWindow);
$('.dropdown-menu').on('click touchstart', function(event) {
event.stopPropagation();
});
// Dynamically force sidenav/dropdown to no higher than browser window
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
$(function() {
$(window).resize(function() {
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
});
});
</script>
</body>
</html>