首页 > 其他分享 >djangorestframework开发配置

djangorestframework开发配置

时间:2023-02-03 17:38:23浏览次数:43  
标签:None code self 配置 djangorestframework 开发 msg data response

  • django 和 restframework 结合。对api再次封装返回结果形如。非drf浏览器状态码返回
  • 基础模型封装
  • 分页格式调整
{
  "msg": 'success',
  "code": 200,
  "data": []
}

后端目录设置

- project
	- apps # 模块
	- project # 项目配置
	- utils # 封装api
		- exceptions.py
		- response.py
		- minxins.py
		- views.py
		- viewsets.py
		- models.py

response

基础api如APIView, GenericAPIView需要发挥 Response。对from rest_framework.response import Response封装

response.py


from rest_framework.response import Response


class CustomResponse(Response):

    def __init__(self, data=None, status=200, code=200, msg='success', template_name=None, headers=None,
                 exception=False, content_type=None):
        super().__init__(data, status, template_name, headers, exception, content_type)

        self.data = {
            'data': [] if data is None else data,
            'code': code,
            'msg': msg
        }

minxins

mixins.py

如果使用ListModelMixin RetrieveModelMixin UpdateModelMixin DestroyModelMixin需要将Response重新构造

from rest_framework import mixins
from utils.response import CustomResponse


class CustomCreateModelMixin(mixins.CreateModelMixin):

    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        return CustomResponse(data=response.data)

如果使用DestroyModelMixin逻辑删除可以重构

def perform_destroy(self, instance):
    """
    存在逻辑删除,逻辑删除,否则直接删除
    """
    try:
        instance.is_delete = True
    except AttributeError:
        instance.delete()
    else:
        instance.save()

exceptions

逻辑中可以直接抛出自定义异常,在exceptions中捕捉异常!此类方式用于处理,多次调用时。可能,这种方式不是一个性能较好的方法!但是确实是一个较快的处理方式。

前端定义规范code。在drf序列化起验证异常权限认证格式不同。所以,在处理前端根据返回结果中msg展示给用户时需要处理。前端或者后端处理都可以。

exceptions.py

from rest_framework.views import (
    exception_handler, status, Response, set_rollback, exceptions
)

from django.http import Http404
import logging

logger = logging.getLogger('django')


class CustomException(Exception):
    # 自定义code
    default_code = 400
    # 自定义 message
    default_message = None

    def __init__(
            self,
            status_code=status.HTTP_200_OK,
            code: int = None,
            message: str = None,
            data=None,
    ):
        self.status = status_code
        self.code = self.default_code if code is None else code
        self.message = self.default_message if message is None else message

        if data is None:
            self.data = {"msg": self.message, "code": self.code, 'data': []}
        else:
            self.data = data


def exc_handler(exc, content):
    """处理特殊异常"""

    if isinstance(exc, Http404):
        return Response({'code': 404, 'data': {}, 'msg': '数据找不到'})

    if isinstance(exc, CustomException):
        return Response(data=exc.data, status=exc.status)
    response = exception_handler(exc, content)
    if response is not None:

        # 处理 验证异常问题
        code = response.status_code
        if code == 400:
            msg = response.data
        else:
            msg = exc.default_detail
        return Response({'code': exc.status_code, 'data': [], 'msg': msg})
    return response

settings

REST_FRAMEWORK = {
    # 身份认证
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
    # 权限认证
    'DEFAULT_PERMISSION_CLASSES': ('utils.permissions.CustomPermission',),
    # 分页
    'DEFAULT_PAGINATION_CLASS': 'utils.pagination.CustomPagination',
    # 过滤
    'DEFAULT_FILTER_BACKENDS': (
        'django_filters.rest_framework.DjangoFilterBackend',
    ),
    # 异常
    'EXCEPTION_HANDLER': 'utils.exceptions.exc_handler'

}

pagination

分页返回格式修改(全局)。

from rest_framework.pagination import PageNumberPagination
from utils.response import CustomResponse


class CustomPagination(PageNumberPagination):
    max_page_size = 100
    page_size_query_param = 'page_size'
    page_size = 15
    
    def get_paginated_response(self, data):
      """统一分页响应格式 可以修改分页的响应参数"""
        return CustomResponse(data=OrderedDict([
            ('count', self.page.paginator.count),
            ('next', self.get_next_link()),
            ('previous', self.get_previous_link()),
            ('results', data)
        ]))


基础模型

定义公共基础model减少不必要的代码

from django.db import models


class TimeBase(models.Model):
    is_delete = models.BooleanField(default=False, null=True, blank=True, verbose_name='是否删除')
    created_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(verbose_name='更新时间', auto_now=True, blank=True, null=True)

    class Meta:
        abstract = True
        ordering = ('-created_at',)

在使用时倒导入并继承

标签:None,code,self,配置,djangorestframework,开发,msg,data,response
From: https://blog.51cto.com/u_14967494/6035925

相关文章

  • 专注陪诊小程序开发-让你就医更安心
     陪诊小程序主要就是一款为空巢老人、工作繁忙的年轻人,年幼的儿童、身体不方便的人士提供线上下单寻求专业人员陪同就医的一款小程序,陪诊员线上接单,线下为患者提供专业的医......
  • 我所说的“隐形开发人员”是什么意思
    昨天我收到了几封读者邮件。他们对我的隐形开发人员的概念感到困惑。在一些文章中,我提倡作为开发人员创造价值和提高生产力。在昨天的文章中,我建议您做的只是勉强过得去......
  • 陪诊app开发|陪诊系统功能这么牛
    随着近些年来市场的变化,陪诊服务也在慢慢的受到人们的关注,自从有了陪诊系统之后,帮助了许许多多独立就医不便的人群,开发搭建一套陪诊系统哪些功能是应当具备的呢?一套好的陪诊......
  • SpringBoot配置属性之Server
    server配置server.address指定server绑定的地址  server.address= 0.0.0.0 #springboot部署服务器端微服务,server.address配置0.0.0.0,否则当微服务的jar......
  • vue.js客服系统实时聊天项目开发(十八)仿淘宝商品页面点在线客服传递产品卡片
    我们在使用淘宝的时候,在商品页面点击在线客服,跳转到客服聊天页以后,会浮动出当前产品信息,可以把产品信息发给客服现在我们也实现了类似功能,可以带着产品信息进聊天页面 ......
  • 清空配置,恢复出厂
    通过conlse线和crt软件连接并登陆设备,然后把设备断电重启。控制台上会打印如下信息,当出现“pressCtrl+B”的时候快速按住“Ctrl+B”进入botroom菜单Systemisstarting.......
  • Java lombok包中的常用注解,便捷化开发POJO类
    lombok包中的一些常用注解如何使用Lombok?Lombok提供注解方式来提高代码的简洁性,常用注解有:   @Data   @Setter@Getter   @NonNull   @Synchronized ......
  • JupyterHub(TLJH)安装卸载, 以及配置GitLab的OAuth登录和开启HTTPS
    介绍JupyterHub是可供多用户使用的JupyterNotebook安装JupyterHub分两个版本,ZerotoJupyterHubwithK8s和TheLittlestJupyterHub前者可以使用K8s集群进行部署,......
  • 插件化开发 -- 系列文章
    插件化开发 .NETConf2020-基于ASP.NETCore构建可热插拔的插件化系统从零开始实现ASP.NETCoreMVC的插件式开发(九)-升级.NET5及启用预编译视图从零开......
  • Spring注解开发
    Spring原始注解Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率。Spring原始注解主要是替代......