DRF - 方法'GET'不允许

时间:2014-01-10 02:40:15

标签: python django django-rest-framework

我正在尝试在Django Rest Framework中设置基于类的视图。

这是我的urls.py -

from django.conf.urls import patterns, include, url
from rest_framework.urlpatterns import format_suffix_patterns
from django.contrib import admin
from TidalDEV import views

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^test/(?P<pk>[0-9]+)/$', views.TESTXMLDetail.as_view()),    
)

这是我的观点 -

import os, tempfile, zipfile
from django.shortcuts import render
from django.core import serializers
from django.core.serializers import serialize
from django.core.servers.basehttp import FileWrapper
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer, XMLRenderer
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, AllowAny
from itertools import chain
from TAPI.renderers import *
from TAPI.models import *
from TAPI.serializers import JobdtlSerializer, JobmstSerializer, TrgjobSerializer, JobdepSerializer

class TESTXMLDetail(APIView):
    permission_classes = (AllowAny,)
    """
    Retrieve, update or delete a snippet instance.
    """
    def get_object(self, pk):
        try:
            mst = Jobmst.objects.db_manager('AdmiralDEV').raw("""
                query1""", [pk])

            dtl = Jobdtl.objects.db_manager('AdmiralDEV').raw("""
                query2""", [pk])        
            dep = Jobdep.objects.db_manager('AdmiralDEV').raw("""
                query3""", [pk])
            trg = Trgjob.objects.db_manager('AdmiralDEV').raw("""
                query4""", [pk])
        except Jobmst.DoesNotExist:
            return HttpResponse(status=404)

        def get(self, request, pk, format=None):
            jobmststring = JobmstSerializer(mst)
            jobdtlstring = JobdtlSerializer(dtl)
            jobdepstring = JobdepSerializer(dep, many=True)
            trgjobstring = TrgjobSerializer(trg, many=True)

            jobmst_serialized = {'jobmst': jobmststring.data}
            jobdtl_serialized = {'jobdtl': jobdtlstring.data}
            jobdep_serialized = [{'jobdep':item} for item in jobdepstring.data]
            trgjob_serialized = [{'trgjob':item} for item in trgjobstring.data]

            jobgroup = jobmst_serialized, jobdtl_serialized, jobdep_serialized, trgjob_serialized

            jobgroupresponse = TESXMLResponse(jobgroup)
            return jobgroupresponse

当我运行URL时,我得到的只是XML格式,但后来却说 -

<detail>Method 'GET' not allowed.</detail>

我已尝试在视图中设置权限类,如上所述,我还在settings.py中添加了以下哪些内容?

  'DEFAULT_PERMISSION_CLASSES': (
   'rest_framework.permissions.AllowAny',
  ),

1 个答案:

答案 0 :(得分:7)

您收到此错误是因为DRF APIView没有get方法(或实际上任何HTTP请求类型的方法)。要使代码正常工作,您可以重命名{{1}方法到get_object(确保添加预期的参数请求和格式),或者您可以编写get方法来返回您的响应:

get