django-rest-framework/api-guide/views/index.html

665 lines
30 KiB
HTML
Raw Normal View History

2014-11-25 19:04:38 +03:00
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
2015-05-15 11:19:49 +03:00
<title>Views - Django REST framework</title>
2014-11-25 19:04:38 +03:00
<link href="../../img/favicon.ico" rel="icon" type="image/x-icon">
<link rel="canonical" href="https://www.django-rest-framework.org/api-guide/views/" />
2014-11-25 19:04:38 +03:00
<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>
2016-05-26 13:48:39 +03:00
#sidebarInclude img {
margin-bottom: 10px;
}
#sidebarInclude a.promo {
2014-11-25 19:04:38 +03:00
color: black;
2016-05-26 13:48:39 +03:00
}
2014-11-25 19:04:38 +03:00
@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>
2015-06-04 17:37:22 +03:00
<a class="repo-link btn btn-inverse btn-small " rel="prev" href="../generic-views/">
2014-11-25 19:04:38 +03:00
Next <i class="icon-arrow-right icon-white"></i>
</a>
2015-06-04 17:37:22 +03:00
<a class="repo-link btn btn-inverse btn-small " rel="next" href="../responses/">
2014-11-25 19:04:38 +03:00
<i class="icon-arrow-left icon-white"></i> Previous
</a>
2015-06-04 17:37:22 +03:00
<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>
2014-11-25 19:04:38 +03:00
<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>
2014-11-25 19:04:38 +03:00
<div class="nav-collapse collapse">
<!-- Main navigation -->
<ul class="nav navbar-nav">
2015-06-04 17:37:22 +03:00
<li >
<a href="../..">Home</a>
</li>
2014-11-25 19:04:38 +03:00
<li class="dropdown">
2014-11-25 19:31:00 +03:00
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a>
2014-11-25 19:04:38 +03:00
<ul class="dropdown-menu">
<li >
2015-06-04 17:37:22 +03:00
<a href="../../tutorial/quickstart/">Quickstart</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../../tutorial/1-serialization/">1 - Serialization</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../../tutorial/2-requests-and-responses/">2 - Requests and responses</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../../tutorial/3-class-based-views/">3 - Class based views</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../../tutorial/4-authentication-and-permissions/">4 - Authentication and permissions</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../../tutorial/5-relationships-and-hyperlinked-apis/">5 - Relationships and hyperlinked APIs</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../../tutorial/6-viewsets-and-routers/">6 - Viewsets and routers</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
<a href="../../tutorial/7-schemas-and-client-libraries/">7 - Schemas and client libraries</a>
</li>
2014-11-25 19:04:38 +03:00
</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 >
2015-06-04 17:37:22 +03:00
<a href="../requests/">Requests</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../responses/">Responses</a>
2014-11-25 19:04:38 +03:00
</li>
<li class="active" >
2015-06-04 17:37:22 +03:00
<a href="./">Views</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../generic-views/">Generic views</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../viewsets/">Viewsets</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../routers/">Routers</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../parsers/">Parsers</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../renderers/">Renderers</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../serializers/">Serializers</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../fields/">Serializer fields</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../relations/">Serializer relations</a>
2014-11-25 19:04:38 +03:00
</li>
2014-12-01 15:20:07 +03:00
<li >
2015-06-04 17:37:22 +03:00
<a href="../validators/">Validators</a>
2014-12-01 15:20:07 +03:00
</li>
2014-11-25 19:04:38 +03:00
<li >
2015-06-04 17:37:22 +03:00
<a href="../authentication/">Authentication</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../permissions/">Permissions</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
<a href="../caching/">Caching</a>
</li>
2014-11-25 19:04:38 +03:00
<li >
2015-06-04 17:37:22 +03:00
<a href="../throttling/">Throttling</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../filtering/">Filtering</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../pagination/">Pagination</a>
2014-11-25 19:04:38 +03:00
</li>
2015-03-06 15:05:16 +03:00
<li >
2015-06-04 17:37:22 +03:00
<a href="../versioning/">Versioning</a>
2015-03-06 15:05:16 +03:00
</li>
2014-11-25 19:04:38 +03:00
<li >
2015-06-04 17:37:22 +03:00
<a href="../content-negotiation/">Content negotiation</a>
2014-11-25 19:04:38 +03:00
</li>
2014-12-18 18:42:42 +03:00
<li >
2015-06-04 17:37:22 +03:00
<a href="../metadata/">Metadata</a>
2014-12-18 18:42:42 +03:00
</li>
<li >
<a href="../schemas/">Schemas</a>
</li>
2014-11-25 19:04:38 +03:00
<li >
2015-06-04 17:37:22 +03:00
<a href="../format-suffixes/">Format suffixes</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../reverse/">Returning URLs</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../exceptions/">Exceptions</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../status-codes/">Status codes</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../testing/">Testing</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../settings/">Settings</a>
2014-11-25 19:04:38 +03:00
</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 >
2015-06-04 17:37:22 +03:00
<a href="../../topics/documenting-your-api/">Documenting your API</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
<a href="../../topics/api-clients/">API Clients</a>
</li>
2015-03-06 15:05:16 +03:00
<li >
2015-06-04 17:37:22 +03:00
<a href="../../topics/internationalization/">Internationalization</a>
2015-03-06 15:05:16 +03:00
</li>
2014-11-25 19:04:38 +03:00
<li >
2015-06-04 17:37:22 +03:00
<a href="../../topics/ajax-csrf-cors/">AJAX, CSRF & CORS</a>
2014-11-25 19:04:38 +03:00
</li>
2015-10-28 14:35:39 +03:00
<li >
<a href="../../topics/html-and-forms/">HTML & Forms</a>
</li>
2014-11-25 19:04:38 +03:00
<li >
2015-06-04 17:37:22 +03:00
<a href="../../topics/browser-enhancements/">Browser Enhancements</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../../topics/browsable-api/">The Browsable API</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
2015-06-04 17:37:22 +03:00
<a href="../../topics/rest-hypermedia-hateoas/">REST, Hypermedia & HATEOAS</a>
2014-11-25 19:04:38 +03:00
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Community <b class="caret"></b></a>
<ul class="dropdown-menu">
2014-11-25 19:04:38 +03:00
<li >
<a href="../../community/tutorials-and-resources/">Tutorials and Resources</a>
</li>
<li >
<a href="../../community/third-party-packages/">Third Party Packages</a>
2014-11-25 19:04:38 +03:00
</li>
<li >
<a href="../../community/contributing/">Contributing to REST framework</a>
2014-11-25 19:04:38 +03:00
</li>
2014-12-18 16:49:50 +03:00
<li >
<a href="../../community/project-management/">Project management</a>
2014-12-18 16:49:50 +03:00
</li>
<li >
<a href="../../community/release-notes/">Release Notes</a>
</li>
<li >
<a href="../../community/3.9-announcement/">3.9 Announcement</a>
</li>
2014-11-25 19:04:38 +03:00
<li >
<a href="../../community/3.8-announcement/">3.8 Announcement</a>
2014-11-25 19:04:38 +03:00
</li>
2014-12-01 15:20:07 +03:00
<li >
<a href="../../community/3.7-announcement/">3.7 Announcement</a>
2014-12-01 15:20:07 +03:00
</li>
2015-08-06 16:31:52 +03:00
<li >
<a href="../../community/3.6-announcement/">3.6 Announcement</a>
2015-08-06 16:31:52 +03:00
</li>
2015-10-28 14:35:39 +03:00
<li >
<a href="../../community/3.5-announcement/">3.5 Announcement</a>
2015-10-28 14:35:39 +03:00
</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>
2014-11-25 19:04:38 +03:00
<li >
<a href="../../community/kickstarter-announcement/">Kickstarter Announcement</a>
2014-11-25 19:04:38 +03:00
</li>
2016-05-26 13:48:39 +03:00
<li >
<a href="../../community/mozilla-grant/">Mozilla Grant</a>
2016-05-26 13:48:39 +03:00
</li>
<li >
<a href="../../community/funding/">Funding</a>
2016-05-26 13:48:39 +03:00
</li>
2014-11-25 19:04:38 +03:00
<li >
<a href="../../community/jobs/">Jobs</a>
2014-11-25 19:04:38 +03:00
</li>
</ul>
</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</div>
</div>
<div class="body-content">
<div class="container-fluid">
<!-- Search Modal -->
2015-06-04 17:37:22 +03:00
<div id="mkdocs_search_modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
2014-11-25 19:04:38 +03:00
<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">
2015-08-06 16:31:52 +03:00
<form role="form" autocomplete="off">
2015-06-04 17:37:22 +03:00
<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>
2014-11-25 19:04:38 +03:00
</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>
2014-11-25 19:04:38 +03:00
</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>
2014-11-25 19:04:38 +03:00
2016-05-26 13:48:39 +03:00
<div class="promo">
<hr/>
<div id="sidebarInclude">
</div>
2014-11-25 19:04:38 +03:00
</ul>
</div>
</div>
<div id="main-content" class="span9">
2015-06-04 17:37:22 +03:00
<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>
2015-06-04 17:37:22 +03:00
</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>
2015-06-04 17:37:22 +03:00
</a>
2014-11-25 19:04:38 +03:00
<h1 id="class-based-views"><a class="toclink" href="#class-based-views">Class-based Views</a></h1>
2014-11-25 19:04:38 +03:00
<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>
2014-11-25 19:04:38 +03:00
</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
2014-11-25 19:04:38 +03:00
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 />
2015-11-04 17:59:23 +03:00
<h2 id="api-policy-attributes"><a class="toclink" href="#api-policy-attributes">API policy attributes</a></h2>
2014-11-25 19:04:38 +03:00
<p>The following attributes control the pluggable aspects of API views.</p>
2015-11-04 17:59:23 +03:00
<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>
2014-11-25 19:04:38 +03:00
<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>
2015-11-04 17:59:23 +03:00
<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>
2015-11-04 17:59:23 +03:00
<h2 id="api-policy-implementation-methods"><a class="toclink" href="#api-policy-implementation-methods">API policy implementation methods</a></h2>
2014-11-25 19:04:38 +03:00
<p>The following methods are called before dispatching to the handler method.</p>
2015-11-04 17:59:23 +03:00
<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>
2014-11-25 19:04:38 +03:00
<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>
2015-11-04 17:59:23 +03:00
<h3 id="initialself-request-42args-kwargs"><a class="toclink" href="#initialself-request-42args-kwargs">.initial(self, request, *args, **kwargs)</a></h3>
2014-11-25 19:04:38 +03:00
<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>
2015-11-04 17:59:23 +03:00
<h3 id="handle_exceptionself-exc"><a class="toclink" href="#handle_exceptionself-exc">.handle_exception(self, exc)</a></h3>
2014-11-25 19:04:38 +03:00
<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>
2015-11-04 17:59:23 +03:00
<h3 id="initialize_requestself-request-42args-kwargs"><a class="toclink" href="#initialize_requestself-request-42args-kwargs">.initialize_request(self, request, *args, **kwargs)</a></h3>
2014-11-25 19:04:38 +03:00
<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>
2015-11-04 17:59:23 +03:00
<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>
2014-11-25 19:04:38 +03:00
<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 />
2015-11-04 17:59:23 +03:00
<h1 id="function-based-views"><a class="toclink" href="#function-based-views">Function Based Views</a></h1>
2014-11-25 19:04:38 +03:00
<blockquote>
<p>Saying [that class-based views] is always the superior solution is a mistake.</p>
2014-11-25 19:04:38 +03:00
<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>
2015-11-04 17:59:23 +03:00
<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>
2014-12-01 15:20:07 +03:00
<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>
2014-11-25 19:04:38 +03:00
<pre><code>from rest_framework.decorators import api_view
2014-12-01 15:20:07 +03:00
@api_view()
2014-11-25 19:04:38 +03:00
def hello_world(request):
return Response({"message": "Hello, world!"})
</code></pre>
2015-06-04 17:37:22 +03:00
<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>
2014-12-01 15:20:07 +03:00
<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>
2015-11-04 17:59:23 +03:00
<h2 id="api-policy-decorators"><a class="toclink" href="#api-policy-decorators">API policy decorators</a></h2>
2015-06-04 17:37:22 +03:00
<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>
2014-11-25 19:04:38 +03:00
<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>
2015-06-04 17:37:22 +03:00
2015-06-23 14:05:53 +03:00
</div> <!--/span-->
</div> <!--/row-->
</div> <!--/.fluid-container-->
</div> <!--/.body content-->
2014-11-25 19:04:38 +03:00
<div id="push"></div>
2015-06-23 14:05:53 +03:00
</div> <!--/.wrapper -->
2014-11-25 19:04:38 +03:00
<footer class="span12">
2015-10-28 14:35:39 +03:00
<p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.
2014-11-25 19:04:38 +03:00
</p>
</footer>
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<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>
2016-05-26 13:48:39 +03:00
<script src="https://fund.django-rest-framework.org/sidebar_include.js"></script>
2015-06-04 17:37:22 +03:00
<script>var base_url = '../..';</script>
<script src="../../mkdocs/js/require.js"></script>
2014-12-11 12:55:10 +03:00
<script src="../../js/theme.js"></script>
2014-11-25 19:04:38 +03:00
<script>
var shiftWindow = function() {
scrollBy(0, -50)
};
2015-06-23 14:05:53 +03:00
2014-11-25 19:04:38 +03:00
if (location.hash) shiftWindow();
window.addEventListener("hashchange", shiftWindow);
$('.dropdown-menu').on('click touchstart', function(event) {
event.stopPropagation();
});
2015-06-23 14:05:53 +03:00
// Dynamically force sidenav/dropdown to no higher than browser window
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
2014-11-25 19:04:38 +03:00
$(function() {
$(window).resize(function() {
2015-06-23 14:05:53 +03:00
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
2014-11-25 19:04:38 +03:00
});
});
</script>
</body>
</html>