标签:eth patch let frame .json com orm back obj
之前通过request.GET 获取get请求的参数,通过request.POST获取post请求的参数
但是request.POST只能处理post请求的form类型的参数
现在使用request.data 来获取参数,不但能获取任意格式参数,而且能处理post,put,delete和patch多种请求
Response可以根据客户端请求的响应格式,响应的返回所需格式
引入status模块,可以使用更明确的标识代替简单的数字
在函数上使用@api_view
或者让类继承APIView
可以确保在视图中接收请求实例,并将上下文添加到响应对象中,从而可以进行内容协商。
@api_view([‘POST‘,‘GET‘]) def snippet_list(request): """ list all snippets or create a snippet :param request: :return: """ if request.method == ‘GET‘: snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets,many=True) print serializer.data return Response(serializer.data) elif request.method == ‘POST‘: data = request.data serializer = SnippetSerializer(data=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)
配合装饰器才能使用Response哦
我们可能见过http://example.com/api/items/4.json这种格式的请求
将urls修改为
from django.conf.urls import url from snippets import views from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ url(r‘^snippets/$‘, views.snippet_list), url(r‘^snippets/(?P<pk>[0-9]+)/$‘, views.snippet_detail), ] urlpatterns = format_suffix_patterns(urlpatterns)
[Django rest-framework] 3-Requests and Responses
标签:eth patch let frame .json com orm back obj
原文地址:http://www.cnblogs.com/lazySmeagol/p/7326382.html