DRF+Vue.JS front-end and back-end separation project example (Part 1): Use Django-Rest-Framework to quickly implement RESTful API interface programming

insert image description here

1. RESTFul API interface requirements and design

This article takes the student information query function as an example, adopts a front-end and back-end separation architecture, and requires the back-end to provide a RESTFul interface.

1.1 This example requires the following query functions:

  • List query, single query
  • Add student information
  • change student information
  • delete student information

1.2 The database student table structure is as follows:

field type length illustrate
name string 30 student name
no string 10 student ID
gender tiny int 1 0: male, 1: female
age int 4 age
class_name string 30 class name
score int 4 score

1.3 According to the REST interface guidelines, the RESTFul style API is designed as follows

Before starting, it is recommended to read REST Interface Fundamentals

operate request type resource request url request data
list query GET http://127.0.0.1:8000/student/ none
single query GET http://127.0.0.1:8000/student/<int:id>/ none
add record POST http://127.0.0.1:8000/student/ {‘name’:‘Jack’, ‘no’:‘A001’,…}
amend record PUT http://127.0.0.1:8000/student/<int:id>/ {‘name’:‘Jack’, ‘no’:‘B001’,…}
Delete Record DELETE http://127.0.0.1:8000/student/<int:id>/ none

Note that the RESTFul style url does not need to add operation verbs in the url, such as http://127.0.0.1:8000/student/list/. Of course, this is also possible, but the recommended way is more concise.

2. Why use Django-rest-framework to develop RESTful API?

Django is the most popular Python web development framework. It provides a complete tool chain such as ORM database encapsulation, templates, views, routing, permissions and authentication, and management background. Various functions are available out of the box. django-rest-framework ( DRF for short) inherits the above advantages of the django framework. Development and deployment can easily complete the REST API development of database CRUD without the support of third-party libraries, and provide comprehensive authentication, hierarchical authority control, Functions such as test pages can quickly develop a set of high-quality REST APIs.

Other frameworks, such as Flask-Rest, need to integrate third-party libraries such as data interface library, authentication, and authority management to complete the actual application. The test also needs the support of third-party tools. In terms of integrated configuration and code quality control , the difficulty obviously increases, and the final input cost often exceeds django-rest-framework. Of course, if you are an experienced Flask developer, it's another matter.

3. Create django project

3.1 Install django-rest-framework

Create and activate a virtual environment

python3 -m venv env_rest
cd env_rest
.\script\activate   # 激活虚拟环境

pip install django
pip install djangorestframework

The command to activate the virtual environment under linux is

source env_test/bin/activate 

Install django-rest-framework

pip install django
pip install djangorestframework

3.2 Create django project and application

Create a new project

django-admin startproject RestTutorial

Under the RestTutorial project, create a new app

cd RestTutorial
python manage.py startapp student_rest

3.3 Modify the global configuration

Open the RestTutorial/RestTutorial/settings.py file and add the following configuration

INSTALLED_APPS = [
    ...
    'rest_framework',   # 导入DRF库
    ‘student_rest’,    # 导入新建app
]

# 设置分页器
REST_FRAMEWORK = {
    
    
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}


Change the language and time zone to Chinese

LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_TZ = False

3.4 Prepare the model

Django uses sqlite3 database by default, you can change the database backend to mysql, postgreSql and other databases you are familiar with, details are skipped.

**Define Student Model**

Open the file RestTutorial/student_rest/models.py, enter the following code

from django.db import models
from django.urls import reverse


# 学生信息model 定义
class Student(models.Model):
    name = models.CharField(max_length=30,verbose_name="姓名")
    no = models.CharField(max_length=10,verbose_name="学号")    
    gender = models.IntegerField(max_length=10,verbose_name="性别")
    age = models.IntegerField(verbose_name="年龄")
    class_name = models.CharField(max_length=30,verbose_name="班级")
    score = models.IntegerField(verbose_name="成绩")

    def __str__(self) -> str:
        return self.name

    class Meta:
        db_table = "student"
        managed = True
        verbose_name = "学生表"
        verbose_name_plural = verbose_name
        unique_together = ['no']

After the model is defined, the database needs to be updated.

python manage.py makemigrations
python manage.py migrate  

3.5 Add the Student model to the management background

For the convenience of adding data, you can add the newly created model to the django management background, and it is more convenient to add initial data

Open the RestTutorial/student_rest/admins.py file and add the following code

from django.contrib import admin
from .models import *

# Register your models here.

class StudentAdmin(admin.ModelAdmin):
    list_display = ['id','name','no','gender','age','class_name','score']
    list_per_page = 10
    
admin.site.register(Student, StudentAdmin)   

3.6 Start the project and add initial data

Create an administrator account and start the project:

python manage.py createsuperuser 
python manage.py runserver 0.0.0.0:8000

If the following information appears, it means that the operation is successful

System check identified 1 issue (0 silenced).
July 06, 2023 - 13:52:06
Django version 3.2.8, using settings 'RestTutorial.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CTRL-BREAK.

Open the browser, enter http://127.0.0.1:8000/admin/, log in, and enter the management background.

Open the student table, add initial data,
insert image description here

4. DRF programming implements RESTful interface

A critical step in DRF programming is to define the Serializer class, which is used to serialize model data. Its usage is very similar to the django Form form.
DRF views can be programmed using functional programming or Class Based View (CBV) view classes, and DRF has built-in various general view classes to simplify programming.

4.1 Custom Serializer class

Create a new file: tutorial/student_rest/serializers.py, and enter the following code

from rest_framework import serializers
from .models import Student


class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = "__all__"

4.2 Realize view function with functional programming

For view programming, DRF provides the @api_view() decorator to implement functional programming. Usually, the response only provides Json byte strings, and does not provide DRF-specific interface test page functions.
Open the RestTutorial/student_rest/views.py, file and output the following code

from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from rest_framework.parsers import JSONParser
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from rest_framework import status
from .models import Student
from .serializers import StudentSerializer


# Create your views here.

# @csrf_exempt
@api_view(['GET','POST'])
def student_list(request):
    if request.method == 'GET':
        # 获取所有数据步骤: 1.获取数据 2.序列化 3.用json格式发送数据
        qs = Student.objects.all()
        serilizer = StudentSerializer(qs, many=True)
        print(serilizer.data)
        return JsonResponse(serilizer.data, safe=False)
    elif request.method =='POST':
        # 新增一条数据的步骤: 1.获取数据 2.反序列化 3.保存至数据库 4.发送结果 
        data = JSONParser().parse(request)
        serilizer = StudentSerializer(data=data)
        if serilizer.is_valid():
            serilizer.save()
            return JsonResponse(serilizer.data, status=status.HTTP_201_CREATED)
        return JsonResponse(serilizer.errors, status=status.HTTP_400_BAD_REQUEST)

def student_detail(request,pk):
    # retrieve, update or delete a row of student model 
    
    # 读取单条数据
    try: 
        row = Student.objects.get(pk=pk)
    except Student.DoesNotExist:
        return HttpResponse(status=status.HTTP_404_NOT_FOUND)
    
    if request.method == 'GET':
        serializer = StudentSerializer(row)
        return JsonResponse(serializer.data)
    elif request.method == 'PUT':
        input_data = JSONParser().parse(request)
        serializer = StudentSerializer(row, data=input_data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=status.HTTP_200_OK)
    elif request.method == 'DELETE':
        row.delete()
        return HttpResponse(status=status.HTTP_204_NO_CONTENT)

Open tutorial/student_rest/urls.py, enter


from django.urls import path
from student_rest import views, views_cbv


urlpatterns = [
    path('v1/', views.student_list),             # 用于函数式View测试, list, create
    path('v1/<int:pk>/', views.student_detail),  # 用于函数式View测试, retrieve, update, delete

]

The v1/ is added to the url mainly to distinguish it from the CBV view class routing in the next chapter.
In the routing configuration file RestTutorial/RestTutorial/urls.py of the open project, add a route

from django.contrib import admin
from django.urls import path,include
from student_rest import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('student/', include('student_rest.urls')),
]

4.3 Run and verify

Run the project,
python manage.py runserver 0.0.0.0:8000

As mentioned earlier, functional programming does not provide a test interface, so a third-party tool is required to test the interface.
Since the browser cannot send post, put, delete messages, it is recommended to use tools such as postman or curl to test
Open postman, query all records: GET http://127.0.0.1:8000/student/v1/,
insert image description here
test the interface for adding data : POST http://127.0.0.1:8000/student/v1/
Note, select raw, json for body, and manually enter the data to be added in json format.
insert image description here
Use the list interface to query again, and you can see that the data has been added successfully.

5. Implement the REST API using view classes

DRF's functional programming is very simple compared to other programming languages. However, as can be seen from the previous chapter, post and put actually need to do verification and storage, and delete needs to do deletion and other actions, and there may be more in actual application. If there are multiple patterns, each class must write a repeat statement. To save these efforts, DRF provides view classes, mixed-in classes to help simplify programming, and also provides the function of testing the interface.

5.1 CBV view class implementation code

Let's create a new file RestTutorial/student_rest/views_cbv.py and enter the following code

from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Student
from .serializers import StudentSerializer
from rest_framework import generics
from rest_framework.permissions import IsAdminUser

class StudentList(generics.ListCreateAPIView):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer

class StudentDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer

All the functions of Chapter 4 are implemented very concisely. Next, add routing for the new view class;
open tutorial/student_rest/urls.py, add

    path("v2/", views_cbv.StudentList.as_view()), # 用于Class-based View测试, list, create
    path("v2/<int:pk>/", views_cbv.StudentDetail.as_view()), # 用于Class-based View测试, retrieve, update, delete

5.2 Verification

Run the project again, this time without the need for third-party tools, you can conduct a complete test
Open the browser, enter http://127.0.0.1:8000/student/v2/, the page is displayed as follows:
insert image description here
the bottom of the page provides learning data The post interface test function.

Then open the detail view page, such as http://127.0.0.1:8000/student/v2/6/, the page is as follows: the
insert image description here
bottom of the page is the test interface for PUT to change data, and there is a delete button on the top for testing the delete interface. The interface data display is also very friendly and easy for front-end developers to read.

For more formal projects, I recommend using the django test module to write automated test scripts and do not need the support of third-party testing tools such as selenium.

Summarize

Use django-rest-framework to develop REST API based on database CRUD, and provide a complete built-in toolbox, which makes the whole development and testing process convenient and fast. Here comes the convenience.
Therefore, using the django-rest-framework framework for REST API development is a very good choice for small and medium projects.

Complete project code: click to download

Guess you like

Origin blog.csdn.net/captain5339/article/details/131572762
Recommended