Django 的 REST framework 基础知识

系列文章目录

提示:阅读本章之前,请先阅读目录


文章目录

  • 系列文章目录
  • 前言
  • 1. 创建django项目
  • 2. 修改settings.py
  • 3. 根目录创建static文件夹
  • 4. 启动项目
  • 5. 创建数据表
  • 6. 创建一个超级管理员
  • 7. 登录django的admin后台
  • 8. 安装 REST framework
  • 9. 配置settings.py
  • 10. 重新生成数据表
  • 11. 配置urls.py路由
  • 12. 访问rest framework的登录
  • 13. 创建course app
  • 14. 配置course的apps.py
  • 15. 编写course的models.py
  • 16. 编写course的admin.py
  • 17. 把course加入app
  • 18. 创建数据表
  • 19. 编写serializers.py
  • 20. Django 原生的FBV和CBV编写接口
  • 21. DRF装饰器api_view
  • 22. DRF类视图接口
  • 23. DRF 通用类视图
  • 24. DRF视图集
  • 25. DRF视图集urls写法
  • 26. DRF的docs接口文档


前言


1. 创建django项目

django-admin startproject 项目名称

Django 的 REST framework 基础知识_第1张图片

2. 修改settings.py

修改

ALLOWED_HOSTS = ["*"]
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = False
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_test',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': 'localhost',
        'PORT': 3308
    }
}

新增

STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATICFIELS_DIRS = [
    os.path.join(BASE_DIR, "staticfiles")
]

3. 根目录创建static文件夹

4. 启动项目

python manage.py runserver

http://127.0.0.1:8000/
Django 的 REST framework 基础知识_第2张图片

5. 创建数据表

python .\manage.py makemigrations
python .\manage.py migrate

6. 创建一个超级管理员

python .\manage.py createsuperuser
用户名 (leave blank to use 'xxxx'): smobee
电子邮件地址: xxxx@qq.com
Password:
Password (again):
密码长度太短。密码必须包含至少 8 个字符。
这个密码太常见了。
密码只包含数字。
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

7. 登录django的admin后台

http://127.0.0.1:8000/admin

Django 的 REST framework 基础知识_第3张图片

8. 安装 REST framework

依赖requirements.txt

asgiref==3.2.7
certifi==2020.4.5.1
chardet==3.0.4
coreapi==2.3.3
coreschema==0.0.4
Django==3.0.6
django-filter==2.2.0
djangorestframework==3.11.0
idna==2.9
importlib-metadata==1.6.0
itypes==1.2.0
Jinja2==2.11.2
Markdown==3.2.2
MarkupSafe==1.1.1
Pygments==2.6.1
pytz==2020.1
requests==2.23.0
sqlparse==0.3.1
uritemplate==3.0.1
urllib3==1.25.9
zipp==3.1.0

官网

https://www.django-rest-framework.org/#installation

pip install djangorestframework
pip install markdown       # Markdown support for the browsable API.
pip install django-filter  # Filtering support

9. 配置settings.py

INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework.authtoken',
]
REST_FRAMEWORK = {
    # 分页器
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    # 分页
    'PAGE_SIZE': 50,
    # 返回的时间格式
    'DATETIME_FORMAT': '%Y-%m-%d %H:%M:%S',
    # 返回的数据格式
    'DEFAULT_RENDER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ],
    # 解析request.data
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser',
    ],
    # 全局权限
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated'
    ],
    # 认证方式
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ]
}

10. 重新生成数据表

python .\manage.py makemigrations

python .\manage.py migrate

Django 的 REST framework 基础知识_第4张图片

11. 配置urls.py路由

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
    path('api-auth/', include('rest_framework.urls')),
    path('admin/', admin.site.urls),
]

12. 访问rest framework的登录

http://127.0.0.1:8000/api-auth/login/

Django 的 REST framework 基础知识_第5张图片
Django 的 REST framework 基础知识_第6张图片

13. 创建course app

python .\manage.py startapp course

Django 的 REST framework 基础知识_第7张图片

14. 配置course的apps.py

class CourseConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'course'
    verbose_name = '课程信息'

15. 编写course的models.py

from django.conf import settings
from django.db import models


class Course(models.Model):
    name = models.CharField(max_length=255, unique=True, help_text='课程名称', verbose_name='课程名称')
    introduction = models.TextField(help_text='课程介绍', verbose_name='课程介绍')
    price = models.DecimalField(max_digits=10, decimal_places=2, help_text='课程价格', verbose_name='课程价格')
    teacher = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, help_text='课程讲师',
                                verbose_name='课程讲师')
    create_at = models.DateTimeField(auto_now_add=True, help_text='创建时间', verbose_name='创建时间')
    update_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '课程信息'
        verbose_name_plural = '课程信息'
        ordering = ('price',)

    def __str__(self):
        return self.name

16. 编写course的admin.py

from django.contrib import admin
from .models import Course


@admin.register(Course)
class CourseAdmin(admin.ModelAdmin):
    # 显示哪些字段
    list_display = ('name', 'introduction', 'teacher', 'price', 'create_at')
    # 搜索字段
    search_fields = list_display
    # 筛选字段
    list_filter = list_display

17. 把course加入app

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'course'
]

18. 创建数据表

python .\manage.py makemigrations

python .\manage.py migrate

在这里插入图片描述

19. 编写serializers.py

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Author : zhongshaofeng
# File : serializers.py
# Time : 2023/6/30 0:06
from django.contrib.auth.models import User
from .models import Course
from rest_framework import serializers


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        # 序列号所有字段,如果要序列化某些字段,写成元祖即可,('id', 'name', )
        fields = '__all__'


class CourseSerializer(serializers.ModelSerializer):
    # 引入外键
    teacher = serializers.ReadOnlyField(source='teacher.username')

    class Meta:
        model = Course
        fields = '__all__'
        # 设置深度
        depth = 2

# 带超链接的
# class CourseSerializer(serializers.HyperlinkedModelSerializer):
#     # 引入外键
#     teacher = serializers.ReadOnlyField(source='teacher.username')
#
#     class Meta:
#         model = Course
#         fields = '__all__'

20. Django 原生的FBV和CBV编写接口

import json

from django.shortcuts import render
from django.http import HttpRequest, JsonResponse, HttpResponse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt

from .models import Course

course_dict = {
    'name': '数学',
    'introduction': '这是一门数学哦',
    'price': 256.01
}


@csrf_exempt
def course_list(request: HttpRequest):
    """
    Django FBV 原生接口
    :param request:
    :return:
    """
    if request.method == 'GET':
        # 查询所有课程
        courses = Course.objects.all().values()
        # 等同于这种返回
        # return HttpResponse(json.dumps(courses), content_type='application/json')
        return JsonResponse(list(courses))

    if request.method == 'POST':
        # post的话,需要引入取消csrf认证
        # 序列化
        course = json.loads(request.body.decode('utf-8'))
        # return HttpResponse(json.dumps(course), content_type='application/json')
        return JsonResponse(course, safe=False)


# 这里的name='dispatch',是因为django路由进来时,先走的dispatch
@method_decorator(csrf_exempt, name='dispatch')
class CourseList(View):
    """
    Django 的 CBV 编写接口
    """
    
    def get(self, request: HttpRequest):
        return JsonResponse(course_dict)

    def post(self, request: HttpRequest):
        course = json.loads(request.body.decode('utf-8'))
        return HttpResponse(json.dumps(course), content_type='application/json')

21. DRF装饰器api_view

@api_view(['GET', 'POST'])
def course_function_api(request: HttpRequest):
    """
    REST framework 的函数式编写接口
    :param request:
    :return:
    """
    if request.method == 'GET':
        s = CourseSerializer(instance=Course.objects.all(), many=True)
        return Response(data=s.data, status=status.HTTP_200_OK)
    elif request.method == 'POST':
        s = CourseSerializer(data=request.data)
        if s.is_valid():
            s.save(teacher=request.user)
            return Response(data=s.data, status=status.HTTP_200_OK)
        else:
            return Response(status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'PUT', 'DELETE'])
def course_detail(request: HttpRequest, pk):
    """
    课程操作详情
    :param request:
    :return:
    """
    try:
        course = Course.objects.get(pk=pk)
    except Course.DoesNotExist:
        return Response(data={"msg": "查无此数据"}, status=status.HTTP_400_BAD_REQUEST)
    else:
        if request.method == 'GET':
            s = CourseSerializer(instance=course)
            return Response(data=s.data, status=status.HTTP_200_OK)
        elif request.method == 'PUT':
            s = CourseSerializer(instance=course, data=request.data)
            if s.is_valid():
                s.save()
                return Response(data=s.data, status=status.HTTP_200_OK)
            else:
                return Response(data={"msg": "该数据无效,无法修改,失败原因:%s" % s.errors}, status=status.HTTP_400_BAD_REQUEST)
        elif request.method == 'DELETE':
            course.delete()
            return Response(data={"msg": "删除成功"}, status=status.HTTP_200_OK)

Django 的 REST framework 基础知识_第8张图片
Django 的 REST framework 基础知识_第9张图片
Django 的 REST framework 基础知识_第10张图片
Django 的 REST framework 基础知识_第11张图片

22. DRF类视图接口

class CourseTwoList(APIView):
    """
    类视图的接口
    """
    def get_obj(self):
        """
        这里写一个通用获取数据
        :return: 
        """
        pass
    
    def get(self):
        pass

    def post(self):
        pass

    def delete(self):
        pass

23. DRF 通用类视图

class GCourseList(generics.ListCreateAPIView):
    """
    通用类视图
    """
    queryset = Course.objects.all()
    serializer_class = CourseSerializer

    def perform_create(self, serializer):
        serializer.save(teacher=self.request.user)

        
class GCourseDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Course.objects.all()
    serializer_class = CourseSerializer

24. DRF视图集

class CourseViewSet(viewsets.ModelViewSet):
    queryset = Course.objects.all()
    serializer_class = CourseSerializer

    def perform_create(self, serializer):
        serializer.save(teacher=self.request.user)

25. DRF视图集urls写法

from django.urls import path, include
from .views import course_list, course_function_api, course_detail, GCourseList, GCourseDetail, CourseViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(prefix="viewsets", viewset=CourseViewSet)
urlpatterns = [
    path('list', course_list),
    path('function/api', course_function_api),
    path('detail/', course_detail),
    path('gcbv/list', GCourseList.as_view()),
    path('gcbv/detail/', GCourseDetail.as_view()),
    path('viewsets', CourseViewSet.as_view(
        {"get": "list", "post": "create"}
    )),
    path('viewsets/', CourseViewSet.as_view(
        {"get": "retrieve", "put": "update", "patch": "partial_update"}
    )),
    path('', include(router.urls))
]

26. DRF的docs接口文档

settings.py

Django 的 REST framework 基础知识_第12张图片

安装插件,coreapi

urls.py 引入路由

Django 的 REST framework 基础知识_第13张图片
Django 的 REST framework 基础知识_第14张图片

你可能感兴趣的:(django,sqlite,python)