我是Django和rest_frameworks的新手。使用REST_Framework的Django应用程序,如下面的
目标是当调用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)
答案 0 :(得分:0)
将.data
添加到json.dumps
中的序列化程序。
r = requests.post(url, data=json.dumps(serializer.data), headers=headers)