前面介绍了DRF搭建的各个功能的实现,本章介绍如何新建一个包含前面所有功能的DRF框架
开始:
第一步:新建一个django项目,新建一个app,配置settings
新建app:python manage.py startapp apptext
配置settings:
在settings后面加入drf相关配置
# rest framework的相关配置
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
# 配置此项为,只有登录认证的管理员才可以访问数据
'rest_framework.permissions.IsAdminUser',
# 配置此项为,任何人都可访问数据,但只有管理员才可增加修改数据
# 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
}
第二步:新建模型
from django.db import models
class Teacher(models.Model):
name = models.CharField(max_length=32)
age = models.IntegerField()
# 将老师与后台管理员进行绑定,后台管理员与老师是一对多关系
permission = models.ForeignKey('auth.User', on_delete=models.CASCADE)
def __str__(self):
return self.name
class Student(models.Model):
name = models.CharField(max_length=32)
age = models.IntegerField()
# 假设每个学生只有一个老师,老师和学生的关系为 “一对多”
my_teacher = models.ForeignKey('Teacher', on_delete=models.CASCADE)
def __str__(self):
return self.name
迁移模型:
python manage.py makemigrations
python manage.py migrate
第三步:在app中新建一个serializers序列化器
from rest_framework import serializers
from apptext.models import Teacher, Student
class TeacherSer(serializers.ModelSerializer):
# 显示所属组的名称
permission = serializers.ReadOnlyField(source='permission.username')
class Meta:
model = Teacher
fields = '__all__'
class StudentSer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Student
fields = '__all__'
第四步:创建views视图
方法一:
from rest_framework import generics, permissions
from apptext.models import Teacher, Student
from apptext.serializers import TeacherSer, StudentSer
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
class TeacherLC(generics.ListCreateAPIView):
queryset = Teacher.objects.all()
serializer_class = TeacherSer
permission_classes = (permissions.IsAuthenticated, )
class TeacherRUD(generics.RetrieveUpdateDestroyAPIView):
queryset = Teacher.objects.all()
serializer_class = TeacherSer
permission_classes = (permissions.IsAuthenticated, )
class StudentLC(generics.ListCreateAPIView):
queryset = Student.objects.all()
serializer_class = StudentSer
permission_classes = (permissions.IsAuthenticated, )
class StudentRUD(generics.RetrieveUpdateDestroyAPIView):
queryset = Student.objects.all()
serializer_class = StudentSer
permission_classes = (permissions.IsAuthenticated, )
@api_view(['GET'])
def api_root(request, format=None):
return Response({
'teachers': reverse('teacher-list', request=request, format=format),
'students': reverse('student-list', request=request, format=format)
})
方法二:
from text.serializers import UserSer, SensorSer
from text.models import User, Sensor
from text.permissions import IsOwnerOrReadOnly
from rest_framework import viewsets, permissions
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSer
permission_classes = (permissions.IsAuthenticated, IsOwnerOrReadOnly)
class SensorViewSet(viewsets.ModelViewSet):
queryset = Sensor.objects.all()
serializer_class = SensorSer
permission_classes = (permissions.IsAuthenticated, )
法一法二任选其一
第五步:编辑urls
法一:
为方便后期开发,在app中新建一个appurls.py
from django.conf.urls import url
from apptext.views import TeacherLC, TeacherRUD, StudentLC, StudentRUD
urlpatterns = [
url(r'^tl/$', TeacherLC.as_view(), name='teacher-list'),
url(r'^tl/(?P<pk>[0-9]+)/$', TeacherRUD.as_view(), name='teacher-detail'),
url(r'^sl/$', StudentLC.as_view(), name='student-list'),
url(r'^sl/(?P<pk>[0-9]+)/$', StudentRUD.as_view(), name='student-detail'),
]
第六步:新建管理员用户
python manage.py createsuperuser
第七步:新建权限
在app中新建permissions.py
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
自定义权限只允许对象的所有者编辑它。
"""
def has_object_permission(self, request, view, obj):
# 读取权限允许任何请求,
# 所以我们总是允许GET,HEAD或OPTIONS请求。
if request.method in permissions.SAFE_METHODS:
return True
# 只有该数据的所有者才允许写权限。
return obj.permission == request.user
在views视图中增加权限
第八步:新增api文档,配置主urls
from django.contrib import admin
from django.urls import path, include
from apptext import appurls
from rest_framework.schemas import get_schema_view
from rest_framework.documentation import include_docs_urls
schema_view = get_schema_view(title='Pastebin API')
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include(appurls)),
path('schema/', schema_view),
path('docs/', include_docs_urls("林应权的API文档")),
# rest登录窗口
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
法二的url配置:
from django.contrib import admin
from django.conf.urls import url, include
from text.views import UserViewSet, SensorViewSet
from rest_framework.routers import DefaultRouter
from rest_framework.documentation import include_docs_urls
router = DefaultRouter()
router.register(r'user', UserViewSet)
router.register(r'sensor', SensorViewSet)
urlpatterns = [
url('admin/', admin.site.urls),
url('api/', include(router.urls)),
url('docs/', include_docs_urls('文档')),
url('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]