mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-15 06:07:41 +03:00
545 lines
38 KiB
HTML
545 lines
38 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 - Renderers</title>
|
|
<link href="http://django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
|
<link rel="canonical" href="http://django-rest-framework.org/api-guide/renderers"/>
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<meta name="description" content="Django, API, REST, Renderers, API Reference, Custom renderers, Advanced renderer usage, Third party packages">
|
|
<meta name="author" content="Tom Christie">
|
|
|
|
<!-- Le styles -->
|
|
<link href="http://django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
|
<link href="http://django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
|
<link href="http://django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
|
<link href="http://django-rest-framework.org/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>
|
|
</head>
|
|
<body onload="prettyPrint()" class="renderers-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/tomchristie/django-rest-framework/tree/master">GitHub</a>
|
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/serializers">Next <i class="icon-arrow-right icon-white"></i></a>
|
|
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/parsers"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
|
<a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="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="http://django-rest-framework.org">Django REST framework</a>
|
|
<div class="nav-collapse collapse">
|
|
<ul class="nav">
|
|
<li><a href="http://django-rest-framework.org">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://django-rest-framework.org/tutorial/quickstart">Quickstart</a></li>
|
|
<li><a href="http://django-rest-framework.org/tutorial/1-serialization">1 - Serialization</a></li>
|
|
<li><a href="http://django-rest-framework.org/tutorial/2-requests-and-responses">2 - Requests and responses</a></li>
|
|
<li><a href="http://django-rest-framework.org/tutorial/3-class-based-views">3 - Class based views</a></li>
|
|
<li><a href="http://django-rest-framework.org/tutorial/4-authentication-and-permissions">4 - Authentication and permissions</a></li>
|
|
<li><a href="http://django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a></li>
|
|
<li><a href="http://django-rest-framework.org/tutorial/6-viewsets-and-routers">6 - Viewsets and routers</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://django-rest-framework.org/api-guide/requests">Requests</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/responses">Responses</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/views">Views</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/generic-views">Generic views</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/viewsets">Viewsets</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/routers">Routers</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/parsers">Parsers</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/renderers">Renderers</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/serializers">Serializers</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/fields">Serializer fields</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/relations">Serializer relations</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/authentication">Authentication</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/permissions">Permissions</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/throttling">Throttling</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/filtering">Filtering</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/pagination">Pagination</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/content-negotiation">Content negotiation</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/format-suffixes">Format suffixes</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/reverse">Returning URLs</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/exceptions">Exceptions</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/status-codes">Status codes</a></li>
|
|
<li><a href="http://django-rest-framework.org/api-guide/testing">Testing</a></li>
|
|
<li><a href="http://django-rest-framework.org/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://django-rest-framework.org/topics/documenting-your-api">Documenting your API</a></li>
|
|
<li><a href="http://django-rest-framework.org/topics/ajax-csrf-cors">AJAX, CSRF & CORS</a></li>
|
|
<li><a href="http://django-rest-framework.org/topics/browser-enhancements">Browser enhancements</a></li>
|
|
<li><a href="http://django-rest-framework.org/topics/browsable-api">The Browsable API</a></li>
|
|
<li><a href="http://django-rest-framework.org/topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a></li>
|
|
<li><a href="http://django-rest-framework.org/topics/rest-framework-2-announcement">2.0 Announcement</a></li>
|
|
<li><a href="http://django-rest-framework.org/topics/2.2-announcement">2.2 Announcement</a></li>
|
|
<li><a href="http://django-rest-framework.org/topics/2.3-announcement">2.3 Announcement</a></li>
|
|
<li><a href="http://django-rest-framework.org/topics/release-notes">Release Notes</a></li>
|
|
<li><a href="http://django-rest-framework.org/topics/credits">Credits</a></li>
|
|
</ul>
|
|
</li>
|
|
</ul>
|
|
<ul class="nav pull-right">
|
|
<!-- TODO
|
|
<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="body-content">
|
|
<div class="container-fluid">
|
|
|
|
<!-- Search Modal -->
|
|
<div id="searchModal" 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">×</button>
|
|
<h3 id="myModalLabel">Documentation search</h3>
|
|
</div>
|
|
<div class="modal-body">
|
|
<!-- Custom google search -->
|
|
<script>
|
|
(function() {
|
|
var cx = '015016005043623903336:rxraeohqk6w';
|
|
var gcse = document.createElement('script');
|
|
gcse.type = 'text/javascript';
|
|
gcse.async = true;
|
|
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
|
|
'//www.google.com/cse/cse.js?cx=' + cx;
|
|
var s = document.getElementsByTagName('script')[0];
|
|
s.parentNode.insertBefore(gcse, s);
|
|
})();
|
|
</script>
|
|
<gcse:search></gcse:search>
|
|
</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">
|
|
<!-- TODO
|
|
<p style="margin-top: -12px">
|
|
<a class="btn btn-mini btn-primary" style="width: 60px">« previous</a>
|
|
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next »</a>
|
|
</p>
|
|
-->
|
|
<div id="table-of-contents">
|
|
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
|
|
<li class="main"><a href="#renderers">Renderers</a></li>
|
|
<li><a href="#how-the-renderer-is-determined">How the renderer is determined</a></li>
|
|
<li><a href="#setting-the-renderers">Setting the renderers</a></li>
|
|
<li><a href="#ordering-of-renderer-classes">Ordering of renderer classes</a></li>
|
|
<li class="main"><a href="#api-reference">API Reference</a></li>
|
|
<li><a href="#jsonrenderer">JSONRenderer</a></li>
|
|
<li><a href="#unicodejsonrenderer">UnicodeJSONRenderer</a></li>
|
|
<li><a href="#jsonprenderer">JSONPRenderer</a></li>
|
|
<li><a href="#yamlrenderer">YAMLRenderer</a></li>
|
|
<li><a href="#xmlrenderer">XMLRenderer</a></li>
|
|
<li><a href="#templatehtmlrenderer">TemplateHTMLRenderer</a></li>
|
|
<li><a href="#statichtmlrenderer">StaticHTMLRenderer</a></li>
|
|
<li><a href="#htmlformrenderer">HTMLFormRenderer</a></li>
|
|
<li><a href="#browsableapirenderer">BrowsableAPIRenderer</a></li>
|
|
<li><a href="#multipartrenderer">MultiPartRenderer</a></li>
|
|
<li class="main"><a href="#custom-renderers">Custom renderers</a></li>
|
|
<li><a href="#example">Example</a></li>
|
|
<li><a href="#setting-the-character-set">Setting the character set</a></li>
|
|
<li class="main"><a href="#advanced-renderer-usage">Advanced renderer usage</a></li>
|
|
<li><a href="#varying-behaviour-by-media-type">Varying behaviour by media type</a></li>
|
|
<li><a href="#underspecifying-the-media-type">Underspecifying the media type</a></li>
|
|
<li><a href="#designing-your-media-types">Designing your media types</a></li>
|
|
<li><a href="#html-error-views">HTML error views</a></li>
|
|
<li class="main"><a href="#third-party-packages">Third party packages</a></li>
|
|
<li><a href="#messagepack">MessagePack</a></li>
|
|
<li><a href="#csv">CSV</a></li>
|
|
<li><a href="#ultrajson">UltraJSON</a></li>
|
|
|
|
<div>
|
|
<hr>
|
|
|
|
<p><strong>The team behind REST framework are launching a new API service.</strong></p>
|
|
|
|
<p>If you want to be first in line when we start issuing invitations, please sign up here:</p>
|
|
|
|
<!-- Begin MailChimp Signup Form -->
|
|
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
|
|
<style type="text/css">
|
|
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
|
|
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
|
|
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
|
|
</style>
|
|
<div id="mc_embed_signup" style="background: rgb(245, 245, 245)">
|
|
<form action="http://dabapps.us1.list-manage1.com/subscribe/post?u=cf73a9994eb5b8d8d461b5dfb&id=cb6af8e8bd" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
|
|
<!-- <label for="mce-EMAIL">Keep me posted!</label>
|
|
--> <input style="width: 90%" type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
|
|
<div class="clear"><input class="btn btn-success" type="submit" value="Yes, keep me posted!" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
|
|
</form>
|
|
</div>
|
|
</style></div>
|
|
</ul>
|
|
|
|
|
|
<!--End mc_embed_signup-->
|
|
</div>
|
|
</div>
|
|
|
|
<div id="main-content" class="span9">
|
|
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/renderers.py"><span class="label label-info">renderers.py</span></a></p>
|
|
<h1 id="renderers">Renderers</h1>
|
|
<blockquote>
|
|
<p>Before a TemplateResponse instance can be returned to the client, it must be rendered. The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client.</p>
|
|
<p>— <a href="https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process">Django documentation</a></p>
|
|
</blockquote>
|
|
<p>REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types. There is also support for defining your own custom renderers, which gives you the flexibility to design your own media types.</p>
|
|
<h2 id="how-the-renderer-is-determined">How the renderer is determined</h2>
|
|
<p>The set of valid renderers for a view is always defined as a list of classes. When a view is entered REST framework will perform content negotiation on the incoming request, and determine the most appropriate renderer to satisfy the request.</p>
|
|
<p>The basic process of content negotiation involves examining the request's <code>Accept</code> header, to determine which media types it expects in the response. Optionally, format suffixes on the URL may be used to explicitly request a particular representation. For example the URL <code>http://example.com/api/users_count.json</code> might be an endpoint that always returns JSON data.</p>
|
|
<p>For more information see the documentation on <a href="content-negotiation">content negotiation</a>.</p>
|
|
<h2 id="setting-the-renderers">Setting the renderers</h2>
|
|
<p>The default set of renderers may be set globally, using the <code>DEFAULT_RENDERER_CLASSES</code> setting. For example, the following settings would use <code>YAML</code> as the main media type and also include the self describing API.</p>
|
|
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
|
'DEFAULT_RENDERER_CLASSES': (
|
|
'rest_framework.renderers.YAMLRenderer',
|
|
'rest_framework.renderers.BrowsableAPIRenderer',
|
|
)
|
|
}
|
|
</code></pre>
|
|
<p>You can also set the renderers used for an individual view, or viewset,
|
|
using the <code>APIView</code> class based views.</p>
|
|
<pre class="prettyprint lang-py"><code>from django.contrib.auth.models import User
|
|
from rest_framework.renderers import JSONRenderer, YAMLRenderer
|
|
from rest_framework.response import Response
|
|
from rest_framework.views import APIView
|
|
|
|
class UserCountView(APIView):
|
|
"""
|
|
A view that returns the count of active users, in JSON or YAML.
|
|
"""
|
|
renderer_classes = (JSONRenderer, YAMLRenderer)
|
|
|
|
def get(self, request, format=None):
|
|
user_count = User.objects.filter(active=True).count()
|
|
content = {'user_count': user_count}
|
|
return Response(content)
|
|
</code></pre>
|
|
<p>Or, if you're using the <code>@api_view</code> decorator with function based views.</p>
|
|
<pre class="prettyprint lang-py"><code>@api_view(['GET'])
|
|
@renderer_classes((JSONRenderer, JSONPRenderer))
|
|
def user_count_view(request, format=None):
|
|
"""
|
|
A view that returns the count of active users, in JSON or JSONp.
|
|
"""
|
|
user_count = User.objects.filter(active=True).count()
|
|
content = {'user_count': user_count}
|
|
return Response(content)
|
|
</code></pre>
|
|
<h2 id="ordering-of-renderer-classes">Ordering of renderer classes</h2>
|
|
<p>It's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an <code>Accept: */*</code> header, or not including an <code>Accept</code> header at all, then REST framework will select the first renderer in the list to use for the response.</p>
|
|
<p>For example if your API serves JSON responses and the HTML browsable API, you might want to make <code>JSONRenderer</code> your default renderer, in order to send <code>JSON</code> responses to clients that do not specify an <code>Accept</code> header.</p>
|
|
<p>If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making <code>TemplateHTMLRenderer</code> your default renderer, in order to play nicely with older browsers that send <a href="http://www.gethifi.com/blog/browser-rest-http-accept-headers">broken accept headers</a>.</p>
|
|
<hr />
|
|
<h1 id="api-reference">API Reference</h1>
|
|
<h2 id="jsonrenderer">JSONRenderer</h2>
|
|
<p>Renders the request data into <code>JSON</code>, using utf-8 encoding.</p>
|
|
<p>Note that non-ascii characters will be rendered using JSON's <code>\uXXXX</code> character escape. For example:</p>
|
|
<pre class="prettyprint lang-py"><code>{"unicode black star": "\u2605"}
|
|
</code></pre>
|
|
<p>The client may additionally include an <code>'indent'</code> media type parameter, in which case the returned <code>JSON</code> will be indented. For example <code>Accept: application/json; indent=4</code>.</p>
|
|
<pre class="prettyprint lang-py"><code>{
|
|
"unicode black star": "\u2605"
|
|
}
|
|
</code></pre>
|
|
<p><strong>.media_type</strong>: <code>application/json</code></p>
|
|
<p><strong>.format</strong>: <code>'.json'</code></p>
|
|
<p><strong>.charset</strong>: <code>None</code></p>
|
|
<h2 id="unicodejsonrenderer">UnicodeJSONRenderer</h2>
|
|
<p>Renders the request data into <code>JSON</code>, using utf-8 encoding.</p>
|
|
<p>Note that non-ascii characters will not be character escaped. For example:</p>
|
|
<pre class="prettyprint lang-py"><code>{"unicode black star": "★"}
|
|
</code></pre>
|
|
<p>The client may additionally include an <code>'indent'</code> media type parameter, in which case the returned <code>JSON</code> will be indented. For example <code>Accept: application/json; indent=4</code>.</p>
|
|
<pre class="prettyprint lang-py"><code>{
|
|
"unicode black star": "★"
|
|
}
|
|
</code></pre>
|
|
<p>Both the <code>JSONRenderer</code> and <code>UnicodeJSONRenderer</code> styles conform to <a href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a>, and are syntactically valid JSON.</p>
|
|
<p><strong>.media_type</strong>: <code>application/json</code></p>
|
|
<p><strong>.format</strong>: <code>'.json'</code></p>
|
|
<p><strong>.charset</strong>: <code>None</code></p>
|
|
<h2 id="jsonprenderer">JSONPRenderer</h2>
|
|
<p>Renders the request data into <code>JSONP</code>. The <code>JSONP</code> media type provides a mechanism of allowing cross-domain AJAX requests, by wrapping a <code>JSON</code> response in a javascript callback.</p>
|
|
<p>The javascript callback function must be set by the client including a <code>callback</code> URL query parameter. For example <code>http://example.com/api/users?callback=jsonpCallback</code>. If the callback function is not explicitly set by the client it will default to <code>'callback'</code>.</p>
|
|
<p><strong>Note</strong>: If you require cross-domain AJAX requests, you may want to consider using the more modern approach of <a href="http://www.w3.org/TR/cors/">CORS</a> as an alternative to <code>JSONP</code>. See the <a href="../topics/ajax-csrf-cors">CORS documentation</a> for more details.</p>
|
|
<p><strong>.media_type</strong>: <code>application/javascript</code></p>
|
|
<p><strong>.format</strong>: <code>'.jsonp'</code></p>
|
|
<p><strong>.charset</strong>: <code>utf-8</code></p>
|
|
<h2 id="yamlrenderer">YAMLRenderer</h2>
|
|
<p>Renders the request data into <code>YAML</code>. </p>
|
|
<p>Requires the <code>pyyaml</code> package to be installed.</p>
|
|
<p><strong>.media_type</strong>: <code>application/yaml</code></p>
|
|
<p><strong>.format</strong>: <code>'.yaml'</code></p>
|
|
<p><strong>.charset</strong>: <code>utf-8</code></p>
|
|
<h2 id="xmlrenderer">XMLRenderer</h2>
|
|
<p>Renders REST framework's default style of <code>XML</code> response content.</p>
|
|
<p>Note that the <code>XML</code> markup language is used typically used as the base language for more strictly defined domain-specific languages, such as <code>RSS</code>, <code>Atom</code>, and <code>XHTML</code>.</p>
|
|
<p>If you are considering using <code>XML</code> for your API, you may want to consider implementing a custom renderer and parser for your specific requirements, and using an existing domain-specific media-type, or creating your own custom XML-based media-type.</p>
|
|
<p><strong>.media_type</strong>: <code>application/xml</code></p>
|
|
<p><strong>.format</strong>: <code>'.xml'</code></p>
|
|
<p><strong>.charset</strong>: <code>utf-8</code></p>
|
|
<h2 id="templatehtmlrenderer">TemplateHTMLRenderer</h2>
|
|
<p>Renders data to HTML, using Django's standard template rendering.
|
|
Unlike other renderers, the data passed to the <code>Response</code> does not need to be serialized. Also, unlike other renderers, you may want to include a <code>template_name</code> argument when creating the <code>Response</code>.</p>
|
|
<p>The TemplateHTMLRenderer will create a <code>RequestContext</code>, using the <code>response.data</code> as the context dict, and determine a template name to use to render the context.</p>
|
|
<p>The template name is determined by (in order of preference):</p>
|
|
<ol>
|
|
<li>An explicit <code>template_name</code> argument passed to the response.</li>
|
|
<li>An explicit <code>.template_name</code> attribute set on this class.</li>
|
|
<li>The return result of calling <code>view.get_template_names()</code>.</li>
|
|
</ol>
|
|
<p>An example of a view that uses <code>TemplateHTMLRenderer</code>:</p>
|
|
<pre class="prettyprint lang-py"><code>class UserDetail(generics.RetrieveUserAPIView):
|
|
"""
|
|
A view that returns a templated HTML representations of a given user.
|
|
"""
|
|
queryset = User.objects.all()
|
|
renderer_classes = (TemplateHTMLRenderer,)
|
|
|
|
def get(self, request, *args, **kwargs)
|
|
self.object = self.get_object()
|
|
return Response({'user': self.object}, template_name='user_detail.html')
|
|
</code></pre>
|
|
<p>You can use <code>TemplateHTMLRenderer</code> either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.</p>
|
|
<p>If you're building websites that use <code>TemplateHTMLRenderer</code> along with other renderer classes, you should consider listing <code>TemplateHTMLRenderer</code> as the first class in the <code>renderer_classes</code> list, so that it will be prioritised first even for browsers that send poorly formed <code>ACCEPT:</code> headers.</p>
|
|
<p><strong>.media_type</strong>: <code>text/html</code></p>
|
|
<p><strong>.format</strong>: <code>'.html'</code></p>
|
|
<p><strong>.charset</strong>: <code>utf-8</code></p>
|
|
<p>See also: <code>StaticHTMLRenderer</code></p>
|
|
<h2 id="statichtmlrenderer">StaticHTMLRenderer</h2>
|
|
<p>A simple renderer that simply returns pre-rendered HTML. Unlike other renderers, the data passed to the response object should be a string representing the content to be returned.</p>
|
|
<p>An example of a view that uses <code>TemplateHTMLRenderer</code>:</p>
|
|
<pre class="prettyprint lang-py"><code>@api_view(('GET',))
|
|
@renderer_classes((StaticHTMLRenderer,))
|
|
def simple_html_view(request):
|
|
data = '<html><body><h1>Hello, world</h1></body></html>'
|
|
return Response(data)
|
|
</code></pre>
|
|
<p>You can use <code>TemplateHTMLRenderer</code> either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.</p>
|
|
<p><strong>.media_type</strong>: <code>text/html</code></p>
|
|
<p><strong>.format</strong>: <code>'.html'</code></p>
|
|
<p><strong>.charset</strong>: <code>utf-8</code></p>
|
|
<p>See also: <code>TemplateHTMLRenderer</code></p>
|
|
<h2 id="htmlformrenderer">HTMLFormRenderer</h2>
|
|
<p>Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing <code><form></code> tags or an submit actions, as you'll probably need those to include the desired method and URL. Also note that the <code>HTMLFormRenderer</code> does not yet support including field error messages.</p>
|
|
<p>Note that the template used by the <code>HTMLFormRenderer</code> class, and the context submitted to it <strong>may be subject to change</strong>. If you need to use this renderer class it is advised that you either make a local copy of the class and templates, or follow the release note on REST framework upgrades closely.</p>
|
|
<p><strong>.media_type</strong>: <code>text/html</code></p>
|
|
<p><strong>.format</strong>: <code>'.form'</code></p>
|
|
<p><strong>.charset</strong>: <code>utf-8</code></p>
|
|
<p><strong>.template</strong>: <code>'rest_framework/form.html'</code></p>
|
|
<h2 id="browsableapirenderer">BrowsableAPIRenderer</h2>
|
|
<p>Renders data into HTML for the Browsable API. This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page.</p>
|
|
<p><strong>.media_type</strong>: <code>text/html</code></p>
|
|
<p><strong>.format</strong>: <code>'.api'</code></p>
|
|
<p><strong>.charset</strong>: <code>utf-8</code></p>
|
|
<p><strong>.template</strong>: <code>'rest_framework/api.html'</code></p>
|
|
<h4 id="customizing-browsableapirenderer">Customizing BrowsableAPIRenderer</h4>
|
|
<p>By default the response content will be rendered with the highest priority renderer apart from <code>BrowseableAPIRenderer</code>. If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the <code>get_default_renderer()</code> method. For example:</p>
|
|
<pre class="prettyprint lang-py"><code>class CustomBrowsableAPIRenderer(BrowsableAPIRenderer):
|
|
def get_default_renderer(self, view):
|
|
return JSONRenderer()
|
|
</code></pre>
|
|
<h2 id="multipartrenderer">MultiPartRenderer</h2>
|
|
<p>This renderer is used for rendering HTML multipart form data. <strong>It is not suitable as a response renderer</strong>, but is instead used for creating test requests, using REST framework's <a href="testing">test client and test request factory</a>.</p>
|
|
<p><strong>.media_type</strong>: <code>multipart/form-data; boundary=BoUnDaRyStRiNg</code></p>
|
|
<p><strong>.format</strong>: <code>'.multipart'</code></p>
|
|
<p><strong>.charset</strong>: <code>utf-8</code></p>
|
|
<hr />
|
|
<h1 id="custom-renderers">Custom renderers</h1>
|
|
<p>To implement a custom renderer, you should override <code>BaseRenderer</code>, set the <code>.media_type</code> and <code>.format</code> properties, and implement the <code>.render(self, data, media_type=None, renderer_context=None)</code> method.</p>
|
|
<p>The method should return a bytestring, which will be used as the body of the HTTP response.</p>
|
|
<p>The arguments passed to the <code>.render()</code> method are:</p>
|
|
<h3 id="data"><code>data</code></h3>
|
|
<p>The request data, as set by the <code>Response()</code> instantiation.</p>
|
|
<h3 id="media_typenone"><code>media_type=None</code></h3>
|
|
<p>Optional. If provided, this is the accepted media type, as determined by the content negotiation stage.</p>
|
|
<p>Depending on the client's <code>Accept:</code> header, this may be more specific than the renderer's <code>media_type</code> attribute, and may include media type parameters. For example <code>"application/json; nested=true"</code>.</p>
|
|
<h3 id="renderer_contextnone"><code>renderer_context=None</code></h3>
|
|
<p>Optional. If provided, this is a dictionary of contextual information provided by the view.</p>
|
|
<p>By default this will include the following keys: <code>view</code>, <code>request</code>, <code>response</code>, <code>args</code>, <code>kwargs</code>.</p>
|
|
<h2 id="example">Example</h2>
|
|
<p>The following is an example plaintext renderer that will return a response with the <code>data</code> parameter as the content of the response.</p>
|
|
<pre class="prettyprint lang-py"><code>from django.utils.encoding import smart_unicode
|
|
from rest_framework import renderers
|
|
|
|
|
|
class PlainTextRenderer(renderers.BaseRenderer):
|
|
media_type = 'text/plain'
|
|
format = 'txt'
|
|
|
|
def render(self, data, media_type=None, renderer_context=None):
|
|
return data.encode(self.charset)
|
|
</code></pre>
|
|
<h2 id="setting-the-character-set">Setting the character set</h2>
|
|
<p>By default renderer classes are assumed to be using the <code>UTF-8</code> encoding. To use a different encoding, set the <code>charset</code> attribute on the renderer.</p>
|
|
<pre class="prettyprint lang-py"><code>class PlainTextRenderer(renderers.BaseRenderer):
|
|
media_type = 'text/plain'
|
|
format = 'txt'
|
|
charset = 'iso-8859-1'
|
|
|
|
def render(self, data, media_type=None, renderer_context=None):
|
|
return data.encode(self.charset)
|
|
</code></pre>
|
|
<p>Note that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the <code>Response</code> class, with the <code>charset</code> attribute set on the renderer used to determine the encoding.</p>
|
|
<p>If the renderer returns a bytestring representing raw binary content, you should set a charset value of <code>None</code>, which will ensure the <code>Content-Type</code> header of the response will not have a <code>charset</code> value set.</p>
|
|
<p>In some cases you may also want to set the <code>render_style</code> attribute to <code>'binary'</code>. Doing so will also ensure that the browsable API will not attempt to display the binary content as a string.</p>
|
|
<pre class="prettyprint lang-py"><code>class JPEGRenderer(renderers.BaseRenderer):
|
|
media_type = 'image/jpeg'
|
|
format = 'jpg'
|
|
charset = None
|
|
render_style = 'binary'
|
|
|
|
def render(self, data, media_type=None, renderer_context=None):
|
|
return data
|
|
</code></pre>
|
|
<hr />
|
|
<h1 id="advanced-renderer-usage">Advanced renderer usage</h1>
|
|
<p>You can do some pretty flexible things using REST framework's renderers. Some examples...</p>
|
|
<ul>
|
|
<li>Provide either flat or nested representations from the same endpoint, depending on the requested media type.</li>
|
|
<li>Serve both regular HTML webpages, and JSON based API responses from the same endpoints.</li>
|
|
<li>Specify multiple types of HTML representation for API clients to use.</li>
|
|
<li>Underspecify a renderer's media type, such as using <code>media_type = 'image/*'</code>, and use the <code>Accept</code> header to vary the encoding of the response. </li>
|
|
</ul>
|
|
<h2 id="varying-behaviour-by-media-type">Varying behaviour by media type</h2>
|
|
<p>In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access <code>request.accepted_renderer</code> to determine the negotiated renderer that will be used for the response.</p>
|
|
<p>For example:</p>
|
|
<pre class="prettyprint lang-py"><code>@api_view(('GET',))
|
|
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
|
|
def list_users(request):
|
|
"""
|
|
A view that can return JSON or HTML representations
|
|
of the users in the system.
|
|
"""
|
|
queryset = Users.objects.filter(active=True)
|
|
|
|
if request.accepted_renderer.format == 'html':
|
|
# TemplateHTMLRenderer takes a context dict,
|
|
# and additionally requires a 'template_name'.
|
|
# It does not require serialization.
|
|
data = {'users': queryset}
|
|
return Response(data, template_name='list_users.html')
|
|
|
|
# JSONRenderer requires serialized data as normal.
|
|
serializer = UserSerializer(instance=queryset)
|
|
data = serializer.data
|
|
return Response(data)
|
|
</code></pre>
|
|
<h2 id="underspecifying-the-media-type">Underspecifying the media type</h2>
|
|
<p>In some cases you might want a renderer to serve a range of media types.
|
|
In this case you can underspecify the media types it should respond to, by using a <code>media_type</code> value such as <code>image/*</code>, or <code>*/*</code>.</p>
|
|
<p>If you underspecify the renderer's media type, you should make sure to specify the media type explicitly when you return the response, using the <code>content_type</code> attribute. For example:</p>
|
|
<pre class="prettyprint lang-py"><code>return Response(data, content_type='image/png')
|
|
</code></pre>
|
|
<h2 id="designing-your-media-types">Designing your media types</h2>
|
|
<p>For the purposes of many Web APIs, simple <code>JSON</code> responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and <a href="http://timelessrepo.com/haters-gonna-hateoas">HATEOAS</a> you'll need to consider the design and usage of your media types in more detail.</p>
|
|
<p>In <a href="http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven">the words of Roy Fielding</a>, "A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.".</p>
|
|
<p>For good examples of custom media types, see GitHub's use of a custom <a href="http://developer.github.com/v3/media/">application/vnd.github+json</a> media type, and Mike Amundsen's IANA approved <a href="http://www.amundsen.com/media-types/collection/">application/vnd.collection+json</a> JSON-based hypermedia.</p>
|
|
<h2 id="html-error-views">HTML error views</h2>
|
|
<p>Typically a renderer will behave the same regardless of if it's dealing with a regular response, or with a response caused by an exception being raised, such as an <code>Http404</code> or <code>PermissionDenied</code> exception, or a subclass of <code>APIException</code>.</p>
|
|
<p>If you're using either the <code>TemplateHTMLRenderer</code> or the <code>StaticHTMLRenderer</code> and an exception is raised, the behavior is slightly different, and mirrors <a href="https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views">Django's default handling of error views</a>.</p>
|
|
<p>Exceptions raised and handled by an HTML renderer will attempt to render using one of the following methods, by order of precedence.</p>
|
|
<ul>
|
|
<li>Load and render a template named <code>{status_code}.html</code>.</li>
|
|
<li>Load and render a template named <code>api_exception.html</code>.</li>
|
|
<li>Render the HTTP status code and text, for example "404 Not Found".</li>
|
|
</ul>
|
|
<p>Templates will render with a <code>RequestContext</code> which includes the <code>status_code</code> and <code>details</code> keys.</p>
|
|
<p><strong>Note</strong>: If <code>DEBUG=True</code>, Django's standard traceback error page will be displayed instead of rendering the HTTP status code and text.</p>
|
|
<hr />
|
|
<h1 id="third-party-packages">Third party packages</h1>
|
|
<p>The following third party packages are also available.</p>
|
|
<h2 id="messagepack">MessagePack</h2>
|
|
<p><a href="http://msgpack.org/">MessagePack</a> is a fast, efficient binary serialization format. <a href="https://github.com/juanriaza">Juan Riaza</a> maintains the <a href="https://github.com/juanriaza/django-rest-framework-msgpack">djangorestframework-msgpack</a> package which provides MessagePack renderer and parser support for REST framework.</p>
|
|
<h2 id="csv">CSV</h2>
|
|
<p>Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. <a href="https://github.com/mjumbewu">Mjumbe Poe</a> maintains the <a href="https://github.com/mjumbewu/django-rest-framework-csv">djangorestframework-csv</a> package which provides CSV renderer support for REST framework.</p>
|
|
<h2 id="ultrajson">UltraJSON</h2>
|
|
<p><a href="https://github.com/esnme/ultrajson">UltraJSON</a> is an optimized C JSON encoder which can give significantly faster JSON rendering. <a href="https://github.com/hzy">Jacob Haslehurst</a> maintains the <a href="https://github.com/gizmag/drf-ujson-renderer">drf-ujson-renderer</a> package which implements JSON rendering using the UJSON package.</p>
|
|
</div><!--/span-->
|
|
</div><!--/row-->
|
|
</div><!--/.fluid-container-->
|
|
</div><!--/.body content-->
|
|
|
|
<div id="push"></div>
|
|
</div><!--/.wrapper -->
|
|
|
|
<footer class="span12">
|
|
<p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
|
|
</footer>
|
|
|
|
<!-- Le javascript
|
|
================================================== -->
|
|
<!-- Placed at the end of the document so the pages load faster -->
|
|
<script src="http://django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
|
<script src="http://django-rest-framework.org/js/prettify-1.0.js"></script>
|
|
<script src="http://django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
|
|
<script>
|
|
//$('.side-nav').scrollspy()
|
|
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 to no higher than browser window
|
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
|
|
|
$(function(){
|
|
$(window).resize(function(){
|
|
$('.side-nav').css('max-height', window.innerHeight - 130);
|
|
});
|
|
});
|
|
</script>
|
|
</body></html>
|