django-rest-framework搭建平台实战教程一:生成数据库数据

首先需要创建一个django-rest-framework项目,如何创建可以参考https://www.django-rest-framework.org/tutorial/quickstart/,不再赘述。

创建完结构如图所示

 

settings.py配置mysql数据库

...
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": "demo1",
        "USER": "root",
        "PASSWORD": "",
        "HOST": "127.0.0.1",
        "PORT": "3306",
        "CHARSET": "utf8mb4"
    }
}

由于官方用mysql包mysqlclient问题比较多,用pymysql可以替代,根目录__init__.py加入代码

import pymysql
pymysql.install_as_MySQLdb()

由于django-admin已经集成了账户权限功能,不是专业开发可以继承自带的表,附加参数放一些需要的数据

from django.db import models
from django.contrib.auth.models import User,Group,Permission


# Create your models here.

class BaseMixin(models.Model):
    _create_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)
    delete_time = models.DateTimeField(null=True)
    update_user_id = models.IntegerField(null=True)
    create_user_id = models.IntegerField(null=True)

    class Meta:
        abstract = True

class DGroup(Group,BaseMixin):
    extra = models.JSONField(max_length=999, default=dict)

class DUser(User,BaseMixin):
    nickName = models.CharField(max_length=200,null=True, blank=True)
    avatar = models.URLField(max_length=1000,null=True, blank=True)
    remark = models.TextField(max_length=10000,null=True,blank=True)
    roles = models.ManyToManyField(DGroup,related_name="DGroup_users")
    extra = models.JSONField(max_length=999, default=dict)

serializers.py根据表字段定义序列化程序。

from django.contrib.auth.models import Group, Permission
from rest_framework import serializers
from demo.authen.models import DUser,DGroup

class DUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = DUser
        exclude = ['password']

class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = DGroup
        fields = "__all__"

class PermissionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = "__all__"

编写CustomViewSet自定义crud接口的实现

from rest_framework import mixins, viewsets
from rest_framework.response import Response


class CustomViewSet(viewsets.ModelViewSet):
    """
    A viewset that provides `retrieve`, `create`, and `list` actions.

    To use it, override the class and set the `.queryset` and
    `.serializer_class` attributes.
    """
    def list(self, request, *args, **kwargs):
        r = super(CustomViewSet, self).list(request, *args, **kwargs)
        return Response({
            "code": 0,
            "data": r.data
        },headers=r.headers)

    def create(self, request, *args, **kwargs):
        request.data['create_user_id'] = request.user.id
        r = super(CustomViewSet, self).create(request, *args, **kwargs)
        return Response({
            "code": 0,
            "data": r.data
        },headers=r.headers)

    def update(self, request, *args, **kwargs):
        r = super(CustomViewSet, self).update(request, *args, **kwargs)
        return Response({
            "code": 0,
            "data": r.data
        },headers=r.headers)

    def destroy(self, request, *args, **kwargs):
        r = super(CustomViewSet, self).destroy(request, *args, **kwargs)
        return Response({
            "code": 0,
            "data": r.data
        },headers=r.headers)

    def retrieve(self, request, *args, **kwargs):
        r = super(CustomViewSet, self).retrieve(request, *args, **kwargs)
        return Response({
            "code": 0,
            "data": r.data
        },headers=r.headers)

views.py使用ViewSet类自动加入crud接口

from django.contrib.auth.models import Permission
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import permissions

from demo.authen.CustomViewSet import CustomViewSet
from demo.authen.models import DUser, DGroup
from demo.authen.serializers import DUserSerializer, GroupSerializer, PermissionSerializer


class DUserViewSet(CustomViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = DUser.objects.all().order_by('-_create_time')
    serializer_class = DUserSerializer
    permission_classes = [permissions.IsAuthenticated,permissions.DjangoModelPermissions]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['username']

class GroupViewSet(CustomViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = DGroup.objects.all()
    serializer_class = GroupSerializer
    permission_classes = [permissions.IsAuthenticated,permissions.DjangoModelPermissions]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['name']

class PermissionViewSet(CustomViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Permission.objects.all()
    serializer_class = PermissionSerializer
    permission_classes = [permissions.IsAuthenticated,permissions.DjangoModelPermissions]

urls.py编写url路由适配view

from django.urls import include, path
from rest_framework import routers
from . import views

router = routers.DefaultRouter()
router.register(r'users', views.DUserViewSet)
router.register(r'groups', views.GroupViewSet)
router.register(r'permission', views.PermissionViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

模块加入settings

...
INSTALLED_APPS = [
    'demo.authen.apps.AuthenConfig',
    ...
]

apps.py修改下name

from django.apps import AppConfig


class AuthenConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'demo.authen'

运行迁移数据库命令

python manage.py makemigrations
python manage.py migrate

django对于model层的配置基本完成,python manage.py runserver启动后访问http://127.0.0.1:8000/users/登录后就可以使用接口

下一篇文章学习编写controller层的代码,实现用户注册和登录,以及判断登录权限。

 

BaseMixin
posted @ 2023-11-01 17:10  紧肛胡撸娃  阅读(207)  评论(0编辑  收藏  举报