需要Django Rest Framework AssertionError HTTPresponse

2024-05-18 23:26:05 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在终端上使用curl执行以下命令时

curl -X POST http://myuser:mypassword@myweb.com:8000/call/make-call/ -d "tutor=1&billed=1"

我得到以下错误

AssertionError at /call/make-call/ Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <type 'NoneType'>

我的观点.py是

@api_view(['GET', 'POST'])
def startCall(request):

    if request.method == 'POST':

        serializer = startCallSerializer(data=request.DATA)

        if serializer.is_valid():

            serializer.save()

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        else:

            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我的serializer.py是

class startCallSerializer(serializers.ModelSerializer):

    class Meta:
        model = call
        fields = ('tutor', 'billed', 'rate', 'opentok_sessionid')

我的url.py是

urlpatterns = patterns(
    'api.views',
    url(r'^call/make-call/$','startCall', name='startCall'),
)

Tags: pyviewapimakeifresponserequeststatus
2条回答

如果request.method == 'POST'测试失败,则函数不返回响应。 (应GET请求)

@api_view(['GET', 'POST'])
def startCall(request):

    if request.method == 'POST':
        serializer = startCallSerializer(data=request.DATA)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
             return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    #Return this if request method is not POST
    return Response({'key': 'value'}, status=status.HTTP_200_OK)

只需添加

#Return this if request method is not POST
    return Response(json.dumps({'key': 'value'},default=json_util.default))

如果在应用程序开发中没有生成错误代码。

我的完整代码:

@csrf_exempt
@api_view(['GET','POST'])
def uploadFiletotheYoutubeVideo(request):
    if request.method == 'POST': 
        file_obj = request.FILES['file']#this is how Django accepts the files uploaded. 
        print('The name of the file received is ')
        print(file_obj.name)
        posteddata = request.data
        print("the posted data is ")
        print(posteddata)
        response = {"uploadFiletotheYoutubeVideo" : "uploadFiletotheYoutubeVideo"}
        return Response(json.dumps(response, default=json_util.default))
    #Return this if request method is not POST
    return Response(json.dumps({'key': 'value'},default=json_util.default))

相关问题 更多 >

    热门问题