Next, in this article, we further introduce the other core components of django-rest-framework. First, let's do the preparatory work:
Request
The new request class was introduced in Django-rest-framework, which inherits from Django's HttpRequest and provides more flexible request handling capabilities. Like request. The Data property is a property that is specifically used as a Web API, similar to request. POST.
Request. POST # processes only the form data, only the HTML ' POST ' action is accepted. Request. # Processing of specific data; Accept HTML ' POST ', ' PUT ' and ' PATCH ' actions.
State code (status codes)
Django-rest-framework provides a well-packaged, more accurate status code for each status code for our use, such as http_400_bad_request.
API views
Django-rest-framework provides @api_view decorators and Apiview classes for Function_based_view and Class_based_view respectively. These wrapper codes ensure that the view receives the request instance and will automatically add the context to response. These wrapper can also automatically return the correct status code and details.
1. Start
Then before the views.py, here we have no need to jsonresponse, so first remove it. Then modify the Snippet_list view in views.py:
Snippets/Views.PyFromRest_frameworkImportStatusFromRest_framework.DecoratorsImportApi_viewFromRest_framework.ResponseImportResponseFromSnippets.ModelsImportSnippetFromSnippets.serializersImportSnippetserializer@api_view([' GET ',' POST '])DefSnippet_list(Request):"" "Show all existing snippet, or create a new snippet" "IfRequest.Method==' GET ':Snippets=Snippet.Objects.All()Serializer=Snippetserializer(Snippets,Many=True)ReturnResponse(Serializer.Data)ElifRequest.Method==' POST ':Serializer=Snippetserializer(Data=Request.DATA)IfSerializeris_valid (): Serializer. () return response ( serializer., Status=status.< Span class= "PLN" >http_201_created) return response (serializer. Errors, Status=status . http_400_bad_request)
The above code is more concise than the code in tutorial 1. You can see that the code is very similar to the use of the form API, and we also use the built-in status code to make the response meaning of the return clearer.
For a separate snippet edit:
@api_view([' GET ',' PUT ',' DELETE '])DefSnippet_detail(Request,Pk):"" "Show, update or delete a snippet" "Try:Snippet=Snippet.Objects.Get(Pk=Pk)ExceptSnippet.Doesnotexist:ReturnResponse(Status=Status.Http_404_not_found)IfRequest.Method==' GET ':Serializer=Snippetserializer(Snippet)ReturnResponse(Serializer.Data)ElifRequest.Method==' PUT ':Serializer=Snippetserializer(Snippet,Data=Request.DATA)IfSerializer.Is_valid():Serializer.Save()ReturnResponse(Serializer.Data)return response (serializer errors, Status=status http_400_bad_request) elif Requestmethod == ' DELETE ' :. () return response ( status=status. Http_204_no_content
As you can see from the code above, we no longer specify the content type in request and response. Request. Data can be used to manipulate JSON data type types or to handle YAML or other data types. At the same time, Django-rest-framework can also response the correct data types according to different situations.
2. Use other data formats
To demonstrate support for multiple data formats, next, we add a suffix to the URL: Http://example.com/api/items/4.json
Add the format parameter for snippet_list and Snippet_detail in snippets/view.py
def snippet_list(request, format=Nonedef snippet_detail(request , PK, format=None...
Update urls.py:
FromDjango.Conf.URLsImportPatterns,UrlFromRest_frameworkurlpatterns import Format_suffix_patterns urlpatterns = Patterns ( ' snippets.views ' , Url (r ' ^snippets/$ ' ' snippet_list ' ), Url ( R ' ^snippets/(? p<pk>[0-9]+) $ ' ' snippet_detail ' Urlpatterns = format_suffix_patterns< Span class= "pun" > (urlpatterns)
The above code is optional, in fact we do not need to add these URL pattern to achieve multi-data format support. But after adding it makes it more intuitive to use.
3. Testing
We can test it in the way we did in the previous tutorial to get all the snippet:
Curl HTTP:127.0.0.1:8000/snippets/[{"id":1,"Title":"","Code":"foo = \" Bar\ "\ n","Linenos":False, "language" : "python" "Style" : "friendly" }, { "id" : 2 "title" "code" : "print \" Hello, world\ "\ n" "Linenos" : Span class= "KWD" >false: " Python " " style ": " friendly " /span>
Use the Accept header information to control the response return format:
Curl http://127.0.0.1:8000/snippets/-H ' Accept:application/json ' # JSON Curl http:// 127.0.0.1:8000/snippets/-H ' accept:text/html ' # HTML
Or use the suffix to control the return format:
Curl http://127.0.0.1:8000/snippets/.json # json suffix Curl http:// 127.0.0.1:8000/SNIPPETS/.API # browsable API suffix
Control the format by modifying the Content-type header of the request:
# using form data POSTCurl-X POST http:127.0.0.1:8000/snippets/-D "Code=print 123"{"id":3,"Title":"","Code":"Print 123","Linenos":False,"Language":"Python","Style":"Friendly"}# use JSON post Curl -x POST http ://127.0.0.1:8000/snippets/-d ' {"Code": "Print 456"} '-H "content-type: Application/json "{" id ": 4 "title" : " "code" : "Print 456" Linenos "true" language ": span class= "str" > "python" "style" : " Friendly "}
or open it directly in the browser:
HTTP://127.0.0.1:8000/snippets/
Original link: http://www.weiguda.com/blog/20/
Django-rest-framework Tutorials: 2. Requests and Responses