官术网_书友最值得收藏!

Creating Django views combined with serializer classes

We have created the necessary model and its serializer. It is time to code the necessary elements to process HTTP requests and produce HTTP responses. Now, we will create Django views that use the ToySerializer class that we created previously to return JSON representations of the entities for each HTTP request that our web service will handle. Open the toys/views.py file. The following lines show the initial code for this file with just one import statement and a comment that indicates we should create the views:

from django.shortcuts import render 
 
# Create your views here. 

We will create our first version of the web service and we will use functions to keep the code as simple as possible. We will work with classes and more complex code in later examples. First, it is very important to understand how Django and Django REST framework work by way of a simple example.

Now, write the following lines in the restful01/toys/views.py file to create a JSONResponse class and declare two functions: toy_list and toy_detail. The code file for the sample is included in the hillar_django_restful_03_01 folder, in the restful01/toys/views.py file:

from django.shortcuts import render 
from django.http import HttpResponse 
from django.views.decorators.csrf import csrf_exempt 
from rest_framework.renderers import JSONRenderer 
from rest_framework.parsers import JSONParser 
from rest_framework import status 
from toys.models import Toy 
from toys.serializers import ToySerializer 
 
 
class JSONResponse(HttpResponse): 
    def __init__(self, data, **kwargs): 
        content = JSONRenderer().render(data) 
        kwargs['content_type'] = 'application/json' 
        super(JSONResponse, self).__init__(content, **kwargs) 
 
 
@csrf_exempt 
def toy_list(request): 
    if request.method == 'GET': 
        toys = Toy.objects.all() 
        toys_serializer = ToySerializer(toys, many=True) 
        return JSONResponse(toys_serializer.data) 
 
    elif request.method == 'POST': 
        toy_data = JSONParser().parse(request) 
        toy_serializer = ToySerializer(data=toy_data) 
        if toy_serializer.is_valid(): 
            toy_serializer.save() 
            return JSONResponse(toy_serializer.data, \
                status=status.HTTP_201_CREATED) 
        return JSONResponse(toy_serializer.errors, \
            status=status.HTTP_400_BAD_REQUEST) 
 
 
@csrf_exempt 
def toy_detail(request, pk): 
    try: 
        toy = Toy.objects.get(pk=pk) 
    except Toy.DoesNotExist: 
        return HttpResponse(status=status.HTTP_404_NOT_FOUND) 
 
    if request.method == 'GET': 
        toy_serializer = ToySerializer(toy) 
        return JSONResponse(toy_serializer.data) 
 
    elif request.method == 'PUT': 
        toy_data = JSONParser().parse(request) 
        toy_serializer = ToySerializer(toy, data=toy_data) 
        if toy_serializer.is_valid(): 
            toy_serializer.save() 
            return JSONResponse(toy_serializer.data) 
        return JSONResponse(toy_serializer.errors, \
status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': toy.delete() return HttpResponse(status=status.HTTP_204_NO_CONTENT)

The highlighted lines show the expressions that evaluate the value of the request.method attribute to determine the actions to be performed based on the HTTP verb. The JSONResponse class is a subclass of the django.http.HttpResponse class. The django.http.HttpResponse superclass represents an HTTP response with string content.

The JSONResponse class renders its content in JSON. The class just declares the __init__ method that creates a rest_framework.renderers.JSONRenderer instance and calls its render method to render the received data in JSON and save the returned byte string in the content local variable. Then, the code adds the 'content_type' key to the response header with 'application/json' as its value. Finally, the code calls the initializer for the base class with the JSON byte string and the key-value pair added to the header. This way, the class represents a JSON response that we use in the two functions to easily return a JSON response in each HTTP request our web service will process. Since Django 1.7, the django.http.JsonResponse class has accomplished the same goal. However, we created our own class for educational purposes in this example as well as to understand the difference between an HttpResponse and a JSONResponse.

The code uses the @csrf_exempt decorator in the two functions to ensure that the view sets a CSRF (short for Cross-Site Request Forgery) cookie. We do this to make it easier to test this example, which doesn't represent a production-ready web service. We will add security features to our RESTful Web Service later. Of course, it is very important to understand that we should never put a web service into production before configuring security and throttling rules.

Note that the previous code has many problems that we will analyze and fix in the forthcoming chapters. However, first, we need to understand how some basic things work.
主站蜘蛛池模板: 义乌市| 宜川县| 彭泽县| 大连市| 尼玛县| 扎赉特旗| 新郑市| 昭平县| 郁南县| 大关县| 锦屏县| 兴仁县| 永平县| 阿瓦提县| 呼和浩特市| 阿巴嘎旗| 凤庆县| 汉源县| 周至县| 台前县| 洱源县| 苍梧县| 封开县| 邵武市| 沁阳市| 灵石县| 白玉县| 偃师市| 黄龙县| 哈尔滨市| 深泽县| 乐平市| 永宁县| 洛宁县| 民勤县| 桃江县| 襄垣县| 防城港市| 泊头市| 太湖县| 河源市|