Django rest_framework请求使用类视图和modelviewset将数据发布到远程服务器

时间:2016-04-20 08:41:39

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

我是Django和rest_frameworks的新手。使用REST_Framework的Django应用程序,如下面的The image shows the Django rest framework

目标是当调用POST时,使用" request.post"将表单data / json发送到远程服务器url。目前代码没有错误,但数据不会发布到远程服务器URL。 我的类视图示例代码如下:

class SnippetViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows containers to be viewed or edited.
"""
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer

@detail_route(methods=['post'])
def snippet_detail(self, request):
    Snippet = self.get_object()
    serializer = SnippetSerializer(data=request.data)
    if serializer.is_valid():
    headers= {"Content-type":"application/json", "encoding":"utf-8"}
    url = "http://198.0.10.1:5000/create?name=rstudio"
    r = requests.post(url, data=json.dumps(serializer), headers =headers)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serializer.errors,
                        status=status.HTTP_400_BAD_REQUEST)

1 个答案:

答案 0 :(得分:0)

.data添加到json.dumps中的序列化程序。

r = requests.post(url, data=json.dumps(serializer.data), headers=headers)