REST : rest_framework.decorators.api_view 实现PATCH

对 http://www.django-rest-framework.org/tutorial/2-requests-and-responses/ 做补充


点击(此处)折叠或打开

  1. @api_view(['GET', 'PATCH', 'DELETE'])
  2. def snippet_detail(request, pk):
  3.     """
  4.     Retrieve, update or delete a snippet instance.
  5.     """
  6.     try:
  7.         snippet = Snippet.objects.get(pk=pk)
  8.     except Snippet.DoesNotExist:
  9.         return Response(status=status.HTTP_404_NOT_FOUND)

  10.     elif request.method == 'PATCH':
  11.         newData = transferPatchData(snippet, request.data)
  12.         serializer = SnippetSerializer(snippet, data=newData)
  13.         if serializer.is_valid():
  14.             serializer.save()
  15.             return Response(serializer.data)
  16.         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

  17. def transferPatchData(obj, reqtData):
  18.     newData = {}
  19.     for attrName in obj.__dict__.keys():
  20.         if re.search(r"^_", attrName):
  21.             continue
  22.         if reqtData.has_key(attrName):
  23.             newData[attrName] = reqtData.get(attrName)
  24.         else:
  25.             newData[attrName] = getattr(obj, attrName)
  26.     return newData

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/26250550/viewspace-2120779/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/26250550/viewspace-2120779/

你可能感兴趣的:(REST : rest_framework.decorators.api_view 实现PATCH)