REST : rest_framework.decorators.api_view 實現PATCH

G8bao7發表於2016-06-23
對  做補充


點選(此處)摺疊或開啟

  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/,如需轉載,請註明出處,否則將追究法律責任。

相關文章