Click to jump to the REST-Framework column directory

Choosing an appropriate data renderer helps to rationalize the interface and make docking easier.

Project configuration

Such as:

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer'.'rest_framework.renderers.BrowsableAPIRenderer']},Copy the code

Includes the return of JSON data as well as the return of the readme API. Of course, if you don’t want to set the rendering mode globally, you can also do this:

from django.contrib.auth.models import User
from rest_framework.renderers import JSONRenderer
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. """
    renderer_classes = [JSONRenderer]

    def get(self, request, format=None) :
        user_count = User.objects.filter(active=True).count()
        content = {'user_count': user_count}
        return Response(content)
Copy the code

Or the way you use decorators:

@api_view(['GET'])
@renderer_classes([JSONRenderer])
def user_count_view(request, format=None) :
    """ A view that returns the count of active users in JSON. """
    user_count = User.objects.filter(active=True).count()
    content = {'user_count': user_count}
    return Response(content)
Copy the code

When using multiple renderers, the default is the preferred renderer with subscript 0, of course you can specify Accept in your request header.

Renderer listing

The renderer class Apply colours to a drawing type instructions
JSONRenderer application/json Render the returned data in a JSON data style that you can useindentThe media type parameter specifies how you indent, for exampleAccept: application/json; indent=4
TemplateHTMLRenderer text/html When Django template data is returned, it returns HTML type data. Unlike other data returned, data returned using this renderer does not require serialization, but does require it when you create and return the Response instance objecttemplate_nameKeyword parameter
StaticHTMLRenderer text/html A renderer that passes rendered HTML as character rendering
BrowsableAPIRenderer text/html Render the data as HTML for the Browsable API
AdminRenderer text/html The renderer works with CRUD-style Webapis, which should also provide a user-friendly interface to manage data
HTMLFormRenderer text/html Render the serialized data as HTML, and the output of the secondary renderer does not contain closed<from>Tags as well as hidden CSRF input or any submit buttons
MultiPartRenderer multipart/form-data; boundary=BoUnDaRyStRiNg This renderer is used to render HTML multi-part form data and is not suitable for use as a response renderer, but rather for creating test requests using the REST framework’s test client and test request factory

Example JSONRenderer response data:

{
    "unicode black star": "★"."value": 999
}
Copy the code

TemplateHTMLRenderer View example:

class UserDetail(generics.RetrieveAPIView) :
    """ A view that returns a templated HTML representation 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')
Copy the code

Example StaticHTMLRenderer view:

@api_view(['GET'])
@renderer_classes([StaticHTMLRenderer])
def simple_html_view(request) :
    data = '<html><body><h1>Hello, world</h1></body></html>'
    return Response(data)
Copy the code

BrowsableAPIRendererReturn example:

AdminRenderer note: Views with nested or tabulated sequences as their input will not work with the AdminRenderer because HTML forms do not support them properly, and links to details pages will only work properly if your data is configured with the correct URL_FIELD_NAME attribute. For example, using the get_absolute_URL method in the serialization model:

class AccountSerializer(serializers.ModelSerializer) :
    url = serializers.CharField(source='get_absolute_url', read_only=True)

    class Meta:
        model = Account
Copy the code

HTMLFormRenderer Note: You can’t use this renderer directly. Instead, you can use it in a template by passing serialized instance objects to the render_form template tag. Refer to the HTML&Forms documentation:

{% load rest_framework %}

<form action="/submit-report/" method="post">
    {% csrf_token %}
    {% render_form serializer %}
    <input type="submit" value="Save" />
</form>
Copy the code

Third-party Components

YAML

python3 -m pip install djangorestframework-yaml
Copy the code
REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework_yaml.parsers.YAMLParser',].'DEFAULT_RENDERER_CLASSES': [
        'rest_framework_yaml.renderers.YAMLRenderer',]}Copy the code

XML

python3 -m pip install djangorestframework-xml
Copy the code
REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework_xml.parsers.XMLParser',].'DEFAULT_RENDERER_CLASSES': [
        'rest_framework_xml.renderers.XMLRenderer',]}Copy the code

JSONP

Warning: If you need cross-domain AJAX requests, you should generally use the more modern approach of CORS as an alternative to JSONP, which is essentially a browser hack and only works on globally readable API endpoints, where GET requests are unauthenticated and do not require any user permissions.

python3 -m pip install djangorestframework-jsonp
Copy the code
REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework_jsonp.renderers.JSONPRenderer',]}Copy the code

MessagePack

MessagePack is a fast and efficient binary serialization format. Juan Riaza maintains the djangorestframework-msgpack software package, which provides MessagePack renderer and parser support for REST frameworks.

XLSX

XLSX is The most popular binary spreadsheet format in The world. Tim Allen of The Wharton School maintains drF-Renderer-XLSX, which enables endpoints to use OpenPyXL as an XLSX spreadsheet. And allow the client to download. You can style the spreadsheet based on each view.

python3 -m pip install drf-renderer-xlsx
Copy the code
REST_FRAMEWORK = {
    ...

    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer'.'rest_framework.renderers.BrowsableAPIRenderer'.'drf_renderer_xlsx.renderers.XLSXRenderer',]}Copy the code

To avoid streaming files without a file name (browsers usually default to Download without an extension), we need to override the Content-Disposition header with mixin, or default to medusa.xlsx if no file name is provided, for example:

from rest_framework.viewsets import ReadOnlyModelViewSet
from drf_renderer_xlsx.mixins import XLSXFileMixin
from drf_renderer_xlsx.renderers import XLSXRenderer

from .models import MyExampleModel
from .serializers import MyExampleSerializer

class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet) :
    queryset = MyExampleModel.objects.all()
    serializer_class = MyExampleSerializer
    renderer_classes = [XLSXRenderer]
    filename = 'medusa.xlsx'
Copy the code

CSV

Comma-separated values are tabulated data formats in plain text that can be easily imported into spreadsheet applications. Mjumbe Poe maintains the DjangoRest Framework-CSV package, which provides CSV renderer support for REST frameworks.

UltraJSON

UltraJSON is an optimized C JSON encoder that can significantly speed up JSON rendering. Jacob Haslehurst maintains the DRF-UJSON-Renderer software package, which uses the UJSON software package for JSON rendering.

Pandas (CSV, Excel, PNG)

Django REST Pandas provides serializers and renderers that support additional data processing and output through the Pandas DataFrame API, Django REST Pandas includes renderers for Pandas style CSV files, Excel workbooks (including.xls and.xlsx), and many other formats, It is maintained by S. Andrew Sheppard as part of the WQ Project.

LaTeX

Rest Framework Latex provides a renderer that outputs PDFS using Laulatex and is maintained by Pebble (S/F Software).