Digging into Django Rest Framework

This article will introduce the core components of Django REST Framework in detail, including Serializers, ViewSets, Routers, permissions and authentication systems, and testing and debugging tools. The article starts from the basics and gradually deepens, aiming to help readers master the skills of building complex APIs using Django REST Framework.

preface

Definition and Purpose of Django REST Framework

The Django REST Framework, often shortened to DRF, is a powerful and flexible Web API toolkit. Using DRF, developers can quickly build scalable and maintainable RESTful API services. DRF provides a complete set of tools and modules, including authentication, permissions, serialization, views, routing, etc., to help us deal with many common problems in web development.

The main purpose of DRF is to make it easy for Django applications to build and manage APIs. In addition, DRF also pays attention to the browsability and ease of use of the API, so that developers can access and interact with the API through a web browser.

Comparison of Django REST framework and other frameworks (such as Flask)

Although the Django REST framework and other Python web frameworks (such as Flask) share the same goal of helping developers build web applications, they differ in design concepts, functions, and usage scenarios.

  • Design concept : DRF is a relatively "heavyweight" framework that provides a complete set of solutions, including models, views, templates, forms, routing, authentication, permissions, and more. While Flask is more lightweight and flexible, it only provides the most basic tools, and other functions need to be realized by installing extensions.
# Django view示例
from django.http import HttpResponse
def hello_world(request):
    return HttpResponse("Hello, World!")

# Flask view示例
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
    return 'Hello, World!'
  • Functions : DRF provides many built-in functions, such as authentication, permissions, serialization, deserialization, views, routing, etc., which have been carefully designed so that developers can focus more on business logic rather than infrastructure construction. Flask, on the other hand, pays more attention to flexibility, which allows developers to choose and customize the functions they need.

  • Usage scenario : If your project needs to quickly build a RESTful API, or needs to be tightly integrated with other parts of Django (such as ORM, template system, etc.), then DRF may be a better choice. If you need more flexibility, or just need to build a simple web service, then Flask might be a better fit.

basic part

Django REST framework installation and setup

Before starting to use the Django REST framework, you first need to install and configure the relevant environment. Assuming you already have Python and Django installed, you can use pip to install DRF:

pip install djangorestframework

Then, you need to rest_frameworkadd to your Django project's INSTALLED_APPSconfiguration:

# settings.py

INSTALLED_APPS = [
    ...,
    'rest_framework',
]

In this way, we have successfully installed and configured the Django REST framework, and then we can start building our first DRF project.

A basic Django REST framework project construction tutorial

In this tutorial, we'll create a simple API for managing book information. First, we need to create a new Django app:

python manage.py startapp books

Then, we need to booksdefine our model in app:

# models.py

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    published_date = models.DateField()

    def __str__(self):
        return self.title

Next, we need to define the corresponding Serializer and Viewset:

# serializers.py

from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['id', 'title', 'author', 'published_date']


# views.py

from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

Finally, we need to urls.pyadd the route in:

# urls.py

from django.urls import include, path
from rest_framework.routers import DefaultRouter
from .views import BookViewSet

router = DefaultRouter()
router.register(r'books', BookViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

The above is the construction process of a basic Django REST framework project. In this example, we create a book information API that can perform CRUD operations.

Basic components in the Django REST framework: Serializers, Viewsets, Routers

In the above example, we used three main components of DRF: Serializers, Viewsets, and Routers. The following is a brief introduction to them:

  • Serializers : Responsible for converting complex data types (such as Django model instances) into Python data types that can be rendered into JSON, XML, etc. At the same time, it can also be used to parse data in the above format and convert it into complex data types.

  • Viewsets : A class for encapsulating view logic. Similar to Django's class view, but provides more REST-related functionality, such as default GET, POST, PUT, PATCH, and DELETE methods.

  • Routers : Responsible for automatically generating URL routes. Similar to Django's URLconf, but it has better support for DRF's Viewsets, and can automatically create corresponding routes according to the methods in Viewset.

In the next sections, we'll dive into how these three components work and how to use them.

Serializers

In the Django REST framework, Serializers play a vital role. They are responsible for transforming complex data types, such as Django model instances or complex querysets, so that they can be rendered into transportable formats like JSON or XML. At the same time, Serializers are also responsible for completing the deserialization work when the data is received, converting the received data into Python data types.

What is Serializer?

Serializer is similar to Django's Form and ModelForm classes, but they not only contain simple data validation functions, but also complex type conversion functions. They can serialize complex data types (convert to Python basic data types), and deserialize serialized data (convert to complex data types).

# serializers.py

from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['id', 'title', 'author', 'published_date']

In the above example, BookSerializerit is a Serializer, which inherits from the ModelSerializer class and is used to serialize and deserialize Book model instances.

How Serializers Work

When serializing objects, Serializers first convert the objects to Python's built-in data types, and then convert those data types into a transportable format. When deserializing, Serializers perform the reverse process, first converting the received data to Python's built-in data types, and then converting these data types to complex data types.

Here is a simple example that demonstrates how to BookSerializerserialize and deserialize using:

# 使用Serializer进行序列化
book = Book.objects.get(id=1)
serializer = BookSerializer(book)
print(serializer.data)
# 输出:{'id': 1, 'title': 'Django for Beginners', 'author': 'William S. Vincent', 'published_date': '2022-07-01'}

# 使用Serializer进行反序列化
data = {'title': 'REST API with Django', 'author': 'William S. Vincent', 'published_date': '2023-07-01'}
serializer = BookSerializer(data=data)
if serializer.is_valid():
    book = serializer.save()
print(book)
# 输出:<Book: REST API with Django>

Examples and usage of Serializers

The most common use case for Serializers is in views, for serializing and deserializing data processed by views.

For example, we can use Serializer in the view to process the POST request from the client and create a new book:

# views.py

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Book
from .serializers import BookSerializer

class BookList(APIView):
    def post(self, request):
        serializer = BookSerializer(data=request.data)
        if serializer.is_valid():
            book = serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

In the above example, we used it in the POST method of the view BookSerializerto deserialize the received data into a Book model instance and save it to the database.

Serializers are widely used. They can be used not only for basic data validation and conversion, but also for complex scenarios, such as processing nested data, custom fields, dynamic fields, etc. After mastering the basic usage, you can further explore various advanced usages of Serializers according to your needs.

ViewSets

In the Django REST framework, ViewSets is an important component that provides a high-level view abstraction, allowing us to more easily implement API interfaces based on RESTful principles.

What are ViewSets?

ViewSet can be seen as a collection of multiple views. In the Django REST framework, ViewSet is similar to the class view (Class-Based Views) in Django, but it provides more default behaviors and wider functions, such as the default implementation of GET, POST, PUT, PATCH and DELETE operations .

# views.py

from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

In the above example, BookViewSetit is a ViewSet. It inherits from the class and implements a complete set of CRUD operations ModelViewSetfor the model.Book

How ViewSets work

ViewSet works very similar to Django's class view. It maps HTTP methods to corresponding methods in ViewSet, for example, GET requests are mapped to listor retrievemethods, POST requests are mapped to createmethods, PUT and PATCH requests are mapped to updatemethods, and DELETE requests are mapped to destroymethods.

Here is a simple example that demonstrates how to BookViewSethandle GET and POST requests using:

# 使用ViewSet处理GET请求
from rest_framework.test import APIRequestFactory

factory = APIRequestFactory()
request = factory.get('/books/')
response = BookViewSet.as_view({'get': 'list'})(request)
print(response.status_code)
# 输出:200

# 使用ViewSet处理POST请求
request = factory.post('/books/', {'title': 'Django REST Framework', 'author': 'Tom Christie', 'published_date': '2023-07-01'})
response = BookViewSet.as_view({'post': 'create'})(request)
print(response.status_code)
# 输出:201

Instance and use of ViewSets

The most common usage scenario of ViewSet is in URLconf, which is used to create URL routes for API interfaces.

For example, we can use in the URLconf BookViewSetto create URL routes for the Books API:

# urls.py

from django.urls import include, path
from rest_framework.routers import DefaultRouter
from .views import BookViewSet

router = DefaultRouter()
router.register(r'books', BookViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

In the above example, we registered in URLconf BookViewSet, and the Django REST framework will automatically BookViewSetcreate a set of URL routes for it, corresponding to various operations defined by it.

The use of ViewSet is very flexible. They can not only be used to implement basic CRUD operations, but also can be used to implement complex logic, such as permission control, filtering, paging, etc. After mastering the basic usage, you can further explore various advanced usages of ViewSet according to your needs.

Routers

In the Django REST framework, Routers provide a concise way for ViewSets to create and manage URL configurations. Using Routers, we can quickly create and configure URLs, reducing repetitive work.

What is a router?

Router can automatically create URL configurations for view sets, and it provides a set of standard URL configurations for CRUD operations for each view set. The use of Router can greatly improve development efficiency and avoid the tedious work of manually creating each URL.

Here is a simple example using Router:

# urls.py

from django.urls import include, path
from rest_framework.routers import DefaultRouter
from .views import BookViewSet

router = DefaultRouter()
router.register(r'books', BookViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

In the above example, we use DefaultRouter to create a router, and then call its register method to register BookViewSet. This automatically creates a standard set of URL configurations for the BookViewSet.

How routers work

When you register a viewset with Router, Router will automatically create a URL configuration for this viewset. This set of URL configuration corresponds to each method of the view set, such as list, create, retrieve, update and destroy.

router = DefaultRouter()
router.register(r'books', BookViewSet)

In the above example, router will create the following URL configuration for BookViewSet:

  • /books/: Corresponding to the and methods BookViewSetof , processing GET and POST requests respectively;listcreate
  • /books/{pk}/: Corresponding to BookViewSetthe retrieve, updateand destroymethods, respectively handle GET, PUT/PATCH and DELETE requests.

Instance and use of Router

In the Django REST framework, there are two common Routers: DefaultRouterand SimpleRouter. DefaultRouterprovides a routing configuration with an additional browser interface, while SimpleRouterprovides a simple basic routing configuration.

The use of Router is very flexible. You can register as many view sets as you need, and you can use different Routers in different Django apps. After mastering the basic usage, you can also delve into how to customize Router, such as custom URL configuration, custom URL name, etc.

Permissions and Authentication

When building an API, permissions and authentication are very important. They determine whether users can access your API and what users can do. Django REST Framework provides a comprehensive permission and authentication system, allowing you to easily control user access.

certified

Authentication is the process of establishing a user's identity. Django REST Framework supports multiple authentication methods, such as SessionAuthentication, TokenAuthentication, BasicAuthentication, etc.

Here is an example of how to use TokenAuthentication in a view:

# views.py

from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

In this example, we set the authentication_classes attribute for the BookViewSet, specifying the use of TokenAuthentication. When a user requests a BookViewSet, Django REST Framework checks that the request's HTTP headers contain a valid token to determine the user's identity.

permissions

Permissions are the rules that determine what an authenticated user can do. Django REST Framework provides a variety of permission management methods, such as IsAuthenticated, IsAdminUser, IsAuthenticatedOrReadOnly, etc.

In the above example, we set the permission_classes attribute for the BookViewSet, specifying the use of IsAuthenticated. This means that only authenticated users can access BookViewSet.

Custom Authentication and Permissions

In addition to using the authentication and permission management methods provided by Django REST Framework, you can also customize authentication and permissions. Custom authentication and permissions allow you to more flexibly control user access rights.

Here's an example of a custom permission class that only allows authors to access their own books:

# permissions.py

from rest_framework import permissions

class IsAuthor(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        return obj.author == request.user

Then you can use this custom permission in your view:

# views.py

from .permissions import IsAuthor
# 其他导入...

class BookViewSet(viewsets.ModelViewSet):
    # 其他代码...
    permission_classes = [IsAuthenticated, IsAuthor]

In this example, the IsAuthor permission class checks each request, and if the requesting user is not the author of the book, the request will be denied.

Testing and Debugging

Testing and debugging are important steps to ensure code quality. Django REST Framework provides a set of tools for testing and debugging APIs.

test

Django REST Framework integrates Django's testing framework and provides some additional functionality for testing APIs. You can use Django REST Framework's APIClient class to simulate an API request and then inspect the response.

Here is a test example:

# tests.py

from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase, APIClient
from .models import Book

class BookTests(APITestCase):
    def setUp(self):
        self.client = APIClient()
        self.book = Book.objects.create(title='Test Book', author='Test Author')

    def test_get_book(self):
        url = reverse('book-detail', kwargs={'pk': self.book.pk})
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['title'], 'Test Book')
        self.assertEqual(response.data['author'], 'Test Author')

In this example, we first create an APIClient and a Book instance in the setUp method. Then, in the test_get_book method, we use the APIClient to make a GET request, and then check the status code and data of the response.

debugging

Django REST Framework provides a browser interface for debugging the API. You can access the API directly in your browser, view response data, or issue POST, PUT, PATCH, and DELETE requests. The browser interface is very intuitive and a great tool for debugging the API.

To use the browser interface, you just need to enable it in settings.py:

# settings.py

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.BrowsableAPIRenderer',
        'rest_framework.renderers.JSONRenderer',
        # 其他渲染器...
    ]
}

In the above setup, we enabled the BrowsableAPIRenderer, which will enable the browser interface. You can now access the API in your browser.

Debugging with tools

There are many tools that can help you debug your API, such as Postman, Insomnia, etc. These tools can simulate various HTTP requests, view request and response details, and save and organize API requests. These tools can be helpful if you need to do complex API debugging.

While testing and debugging can take some time, they are key to code quality. When writing code, don't forget to write tests and debug.

Summarize

So far, we have given an in-depth overview of Django REST Framework. We started by covering the basics of Django REST Framework, and then dived into Serializers, ViewSets, and Routers. We also discussed the permissions and authentication system, and how to test and debug it.

Django REST Framework provides many powerful tools that make building complex APIs easy. However, mastering these tools takes time and practice. I hope this article helps you start your Django REST Framework journey.

Finally, I want to reiterate some key points we discussed in the article:

  • Serializers are used for data serialization and deserialization.
  • ViewSets are classes that handle view logic.
  • Routers are responsible for URL generation and distribution.
  • Django REST Framework provides a powerful permission and authentication system.
  • You can use Django REST Framework's testing tools and debugging interface to test and debug your API.
  • If it is helpful, please pay more attention to the personal WeChat public account: [Python full perspective] TeahLead_KrisChang, 10+ years of experience in the Internet and artificial intelligence industry, 10+ years of experience in technology and business team management, Tongji Software Engineering Bachelor, Fudan Engineering Management Master, Aliyun certified cloud service senior architect, head of AI product business with hundreds of millions of revenue.

Guess you like

Origin blog.csdn.net/magicyangjay111/article/details/131708711