如何在Django Rest Framework中获取xml格式

时间:2016-12-08 19:00:30

标签: python xml django rest django-rest-framework

我试图在Django Rest FrameWork中获取xml格式,我尝试了Django Rest Framework提供的教程,我是django的新手,我做了以下内容。

settings.py

 INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework',
        'books',
        'users',
    ]

urls.py

from django.conf.urls import url
from django.contrib import admin
from books.views import *
from users.views import *
from rest_framework.urlpatterns import format_suffix_patterns

    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^books/all/$', all_books),
        url(r'^user/', get_user)
    ]

    urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html','xml'])

views.py

from rest_framework.response import Response
from rest_framework.decorators import api_view
from books.serializers import *
from books.models import *

# Create your views here.

@api_view(['GET'])
def all_books(request):
    books = Book.objects.all()
    serializers = BookSerializer(books,many=True)
    return Response(serializers.data)

当我尝试访问xml数据时,我通过执行?format = xml

来获取此错误
{"detail":"Not found."}

教程链接http://www.django-rest-framework.org/api-guide/format-suffixes/

1 个答案:

答案 0 :(得分:2)

实际上你的settings.py缺少xml解析器配置。

  1. 安装rest_framework_xmlpip install djangorestframework-xml
  2. settings.py
  3. 中更新INSTALLED_APPS
    INSTALLED_APPS = [
      'django.contrib.admin',
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.messages',
      'django.contrib.staticfiles',
      'rest_framework',
      'rest_framework_xml',
      'books',
      'users',
    ]
    
    1. settings.py
    2. 中添加xml解析器
      REST_FRAMEWORK = {
        'DEFAULT_PARSER_CLASSES': (
          'rest_framework_xml.parsers.XMLParser',
        ),
          'DEFAULT_RENDERER_CLASSES': (
          'rest_framework_xml.renderers.XMLRenderer',
        ),
      }