Custom django rest parser

2019-08-06 10:51发布

问题:

This is my code:

class lista_libros(APIView):
def post(self, request, format=None): #, format=None
    cadena64 = request.data
    xmlfile = base64.b64decode(cadena64)
    #serializer = PruebaSerializer(data = xmlfile)
    #if serializer.is_valid():
        #serializer.save()
        #return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(xmlfile)

This is what I get:

<?xml version="1.0" encoding="utf-8"?>
<root>&lt;libro&gt;
&lt;nombre&gt;Juego de tronos&lt;/nombre&gt;
&lt;autor&gt;Pablo Perez.&lt;/autor&gt;
&lt;categoria&gt;Fantasia&lt;/categoria&gt;
&lt;editorial&gt;Mexicana&lt;/editorial&gt;
&lt;fecha_pub&gt;1992&lt;/fecha_pub&gt;
&lt;no_pag&gt;5000&lt;/no_pag&gt;
&lt;/libro&gt;</root>

Why the lower and greater than symbols appear like &lt and &gt instead < and >

this code is just for trying to POST a base64 string and decode it into a xml file.

回答1:

That is because the renderer that was used to render the response is HTMLRenderer. DRF determine the renderer to use by using content negotiation:

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.

The basic process of content negotiation involves examining the request's Accept 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 http://example.com/api/users_count.json might be an endpoint that always returns JSON data.

Use .xml at the end of the URL and it should pick XMLRenderer.

In order to limit the response to xml, specify XMLRenderer in you view:

class MyView(APIView):

    renderer_classes = (XMLRenderer,)

    ...