自定义django休息解析器 [英] Custom django rest parser

查看:260
本文介绍了自定义django休息解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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)

这是我得到的:

<?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>

为什么较低和较大的符号显示为& lt和& gt而是<和

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

此代码仅用于尝试POST一个base64字符串并将其解码为一个xml文件。

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

推荐答案

这是因为用于呈现响应的渲染器是HTMLRenderer。 DRF决定渲染器使用使用内容协商

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


视图的有效渲染器集始终被定义为
类的列表。当输入视图时,REST框架将对传入的请求执行内容
协商,并确定最多的
适当的渲染器来满足请求。

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.

内容协商的基本过程包括检查
请求的Accept标头,以确定在
中响应中期望的媒体类型。可选地,URL上的格式后缀可以用于
明确请求特定表示。例如URL
http://example.com/api/users_count.json 可能是
总是返回JSON数据的端点。

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.

最后使用 .xml 的URL,它应该选择XMLRenderer。

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

为了限制对xml的响应,请在您的视图中指定XMLRenderer:

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

class MyView(APIView):

    renderer_classes = (XMLRenderer,)

    ...

这篇关于自定义django休息解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆