DRF notes (2): DRF framework first experience

DRF notes (1): Manual implementation of common APIs records how to manually implement common API types based on Django. This note records the experience of simple use of the DRF framework.

Code repo mentioned in notes: https://github.com/yexia553/drf

Installation and Configuration Modifications

  • Before installing DRF,
    install Django before installing drf
pip install djangorestframework
  • Modify the settings.py file of Django
    and add 'rest_framework' to 'INSTALLED_APPS', as follows
INSTALLED_APPS = [
    ...
    'rest_framework',
]

Write a serializer

The meaning of serialization and deserialization is actually to use Django's Model to modify the data in the database in a certain format (such as dict into json) and then return it to the api requester and write the data obtained from the api request into the database the process of.

Create a new serializers.py file in the 'book' app, the file content is as follows:

from rest_framework import serializers
from .models import BookInfo


class BookInfoSerializer(serializers.ModelSerializer):
    """定义序列化器"""
    class Meta:
        model = BookInfo  # 指定作用的模型
        fields = '__all__'  # 指定序列化的字段,这里让所有字段都能被序列化

The function of the above piece of code is actually to replace the process of using the model to obtain data from the database and write the data obtained from the API to the database repeatedly when I manually implement the API. The following lists a query for a specific book Book example.

try:
    book = BookInfo.objects.get(id=pk)
except BookInfo.DoesNotExist:
    return HttpResponse({
    
    'mesage':'查询的数据不存在'}, status=404)

res = {
    
    
    'id': book.id,
    'title': book.title,
    'read': book.read,
    'pub_date': book.pub_date,
    'comment': book.comment,
    'image': book.image.url if book.image else ''
}

write view

Add a new view class in view.py of book, as follows:

from rest_framework.viewsets import ModelViewSet


class BookInfoView(ModelViewSet):
    '''图书信息视图,包含增删查改所有操作'''
    queryset = BookInfo.objects.all()  # 指定可以作用的数据范围

    serializer_class = BookInfoSerializer  # 指定序列化器

The above view class has only three lines, but it implements all the functions of the two view classes BookListView and BookDetailView in Note 1. It can be seen that the DRF framework is still very convenient, reducing a lot of repetitive code writing work.

Modify url configuration

  • The route configuration in the demo can not be modified at all.
    The url starting with books/ will lead to the route in the book app, as follows:
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('books/', include('book.urls') )
]
  • Modify the url in book
    Modify book/urls.py as follows:
from django.conf.urls import url
from rest_framework.routers import DefaultRouter
from . import views


router = DefaultRouter()  # DefaultRouter会帮助生成api的路由

# 第一个参数是路由,这里置空,这样配合跟路由中的配置,
#就可以实现http://127.0.0.1/books/ 指向views.BookInfoView,
router.register('', views.BookInfoView, basename='books')

# Django只会在urlpatterns中寻找路由,所以要把上面配置生成的url加到urlpatterns中
urlpatterns = [
    # url(r'^$', views.BookListView.as_view()),
    # url(r'^(?P<pk>\d+)$', views.BookDetailView.as_view()),
] + router.urls

test


  • After running the project through browser testing , enter the addresses in the browser:

    1. http://127.0.0.1:8000/books/
    • This url is the API for querying all book information, and you can see the data in the current data in the browser;
    • At the bottom of the page is a form, and there is a POST button in the lower right corner, which corresponds to the POST API, which is to create a book
    1. http://127.0.0.1:8000/books/2
    • When this url is entered in the browser, it is actually a query API, but it is to query the information of the book whose id is 2;
    • But when you enter, you will see a red DELETE button in the upper right corner of the page, which corresponds to the DELETE API;
    • The lower part of the page is a table, and there is a blue PUT button in the lower right corner, which corresponds to the PUT API;
  • There is a file drf_first_seen.py in the test path through the code test
    . Running this file will return the success or result of each API test, as follows:

(venv): python drf_first_seen.py 
测试查询具体书本信息API成功
测试创建书本API成功
测试查询所有书本信息API成功
测试更新API成功
测试删除API成功

Synchronously published on personal site, welcome to visit: panzhixiang.cn

Guess you like

Origin blog.csdn.net/u013117791/article/details/123909792