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.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.70.101