django Rest Framework
-
安装:pip install django djangorestframework -i Simple Index --trusted-host mirrors.aliyun.com
-
创建conda虚拟环境:conda create -n py39 python=3.9
-
激活py39虚拟环境:conda activate py39 退出是:conda deactivate py39
-
创建django项目:django-admin startproject meng
GET 路由地址 获取数据 请求方式 请求地址 后端操作 POST /students 增加数据 GET /students/<pk> 已id获取单条数据 PUT /students/<pk> 指定id修改数据 DELETE /students/<pk> 指定id删除数据
1、使用rest_framework教程
-
首先在settings中INSTALLED_APPS中倒入:rest_framework
INSTALLED_APPS=[ ...... 'rest_framework', ]
-
首先创建APP:django-admin startapp stuapi
-
创建模型操作类
class Student(models.Model): # 模型字段 name = models.CharField(max_length=100,verbose_name="姓名") sex = models.BooleanField(default=1,verbose_name="性别") age = models.IntegerField(verbose_name="年龄") classmate = models.CharField(max_length=5,verbose_name="班级编号") description = models.TextField(max_length=1000,verbose_name="个性签名") class Meta: db_table = "tb_student" verbose_name = "学生" verbose_name_plural = verbose_name
-
配置MySQL数据错误
1、在主目录下得__init__.py下添加两行代码 from pymysql import install_as_MySQLdb install_as_MySQLdb()
-
配置数据库后迁移数据 : python manage.py makemigrations和同步到数据库:python manage.py migrate
-
原生代码编写:views.py
from django.views import View from django.http.response import JsonResponse from .models import Student """ POST /students/ 添加一个学生信息 GET /students/ 获取所有学生信息 GET /students/<pk>/ 获取一个学生信息 PUT /students/<pk>/ 更新一个学生信息 DELETE /students/<pk>/ 删除一个学生信息 一个路由对应一个使徒类,所以我们可以把5个API分成2个类来完成 """ class StudentView(View): def post(self,request): """添加一个学生信息""" # 1、就收客户单提交的数据 name = request.POST.get("name") sex = request.POST.get("sex") age = request.POST.get("age") classmate = request.POST.get("classmate") description = request.POST.get("description") # 2、操作数据库,保存数据 instance = Student.objects.create( name = name, sex = sex, age = age, classmate = classmate, description = description ) # 3、返回结果 return JsonResponse(data={ "pk":instance.pk, "name":instance.name, "sex":instance.sex, "age":instance.age, "classmate":instance.classmate, "description":instance.description, },status=201) def get(self,request): # 获取所有的数据放回到json strlist = list(Student.objects.values()) return JsonResponse(strlist,status=204,safe=False)
-
主路由urls.py
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('api/',include("stuapi.urls")) ]
-
次路由urls.py
from django.urls import path from . import views urlpatterns = [ path('students/', views.StudentView.as_view()), ]
2、序列化rest_framework 代码使用
-
上面的学习信息模型已经创建了,就不需要在创建了
-
开始创建序列化器,首先创建一个serializers.py文件,这个就是序列化器代码如下:
from rest_framework import serializers from stuapi import models as stuapiModels # 这里是模型的序列化器 class StudentMS(serializers.ModelSerializer): class Meta: model = stuapiModels.Student fields='__all__'
-
这里是views.py中视图模型:
from rest_framework.viewsets import ModelViewSet from stuapi import models as stuapiModels from .serializers import StudentMS class StudentMVS(ModelViewSet): queryset = stuapiModels.Student.objects.all() serializer_class = StudentMS
-
开始配置路由urls.py这个是子类路由代码如下:
from rest_framework.routers import DefaultRouter from . import views router = DefaultRouter() router.register('stu',views.StudentMVS,basename='stu') urlpatterns = [ ]+router.urls
-
这个是主路由代码如下:
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('api/',include("stuapi.urls")), path('api/',include("students.urls")) # 可以重名, ]
3、反序列化rest_framework代码使用
-
反序列化需要对提交的数据进行代码的校验,然后再进行保存,防止恶意提交数据
4、rest_framework中装饰器的使用
-
在视图view中引入装饰器:from rest_framework.decorators import api_view 在引入返回:from rest_framework.response import Response
-
编写方法:
# rest_framework装饰器的使用 @api_view(["GET"]) # 只允许get方式请求 def xxxx(request): return Res({"data":"ok"})