rest_framework07:权限/频率/过滤组件/排序/异常处理封装Response对象

权限

写一个类,继承BasePermission,如果通过返回True,否则False

这里需要配合认证使用,否则没有user_type属性。

from rest_framework.permissions import BasePermissionclass UserPermission(BasePermission):def has_permission(self, request, view):# 不是超级用户不能访问# 如果认证已经通过了, request 内勇敢有user对象。# 当前登录用户user = request.userif user.user_type == 1:return Trueelse:return False

局部使用

在视图类添加

class TestView(APIView):permission_classes = [app_auth.UserPermission]

全局使用

在配置文件添加

REST_FRAMEWORK={'DEFAULT_PERMISSION_CLASSES':['app_authentication.app_auth.UserPermission',]
}

局部禁用

class TestView(APIView):permission_classes = []

内置频率

全局配置

未登录用户限制

REST_FRAMEWORK={'DEFAULT_THROTTLE_CLASSES': ('rest_framework.throttling.AnonRateThrottle',),'DEFAULT_THROTTLE_RATES': {'anon': '3/m',}

过滤组件

组件是django的,放在rest framework使用

1.安装

pip install django-filter

2.注册

INSTALLED_APPS = [...'django_filters',  # 需要注册应用,
]

3.配置

全局配置为例

REST_FRAMEWORK = {...'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}
from rest_framework.generics import ListAPIView
from app01.models import Book
from app_authentication.ser import BookModelSerializerclass BookView(ListAPIView):queryset = Book.objects.all()serializer_class = BookModelSerializerfilter_fields = ('name', 'price')

访问:http://127.0.0.1:8000/app_authentication/bookview/?price=22.10

排序

from rest_framework.filters import OrderingFilter
class Book2View(ListAPIView):queryset = Book.objects.all()serializer_class = BookModelSerializer# 如果有局部过滤功能,在列表添加filter_backends = [OrderingFilter]ordering_fields=('id','price')

访问:

倒序:http://127.0.0.1:8000/app_authentication/book2view/?ordering=-price

正序:http://127.0.0.1:8000/app_authentication/book2view/?ordering=price

异常处理

1.统一抛出固定格式错误信息

2.记日志

自定义异常方法,替换全局使用

# 自定义异常
from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status
def my_exception_handler(exc,context):response=exception_handler(exc,context)# response 两种情况# None drf 没有处理# Response 对象,django处理,但不符合需求print(type(exc))if not response: # 非空if isinstance(exc,ZeroDivisionError):return Response(data={'status':777,'msg':'除以0错误'+str(exc)},status=status.HTTP_400_BAD_REQUEST)return Response(data={'status': 999, 'msg':  str(exc)}, status=status.HTTP_400_BAD_REQUEST)else:return Response(data={'status': 888, 'msg': response.data.get('detail')}, status=status.HTTP_400_BAD_REQUEST)

settings.py

REST_FRAMEWORK={...'EXCEPTION_HANDLER':'app_authentication.app_auth.my_exception_handler'
}

封装Response对象

class APIResponse(Response):def __init__(self,code=100,msg='成功',data=None,status=None,headers=None,**kwargs):dic={'code':code,'msg':msg}if data:dic={'code':code,'msg':msg,'data':data}# 可以多添加参数dic.update(kwargs)super().__init__(data=dic,status=status,headers=headers)

使用

from app_authentication.app_auth import APIResponse
class TestView4(APIView):def get(self,request,*args,**kwargs):return APIResponse(data={"nane":'abc'},token="sldjfl",aa="123123")#  return APIResponse(data={"nane":'abc'})
#  return APIResponse(token="sldjfl",aa="123123")

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/280426.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

在阿里,我们如何管理测试环境

为什么80%的码农都做不了架构师?>>> 作者:林帆(花名金戟),阿里巴巴研发效能部技术专家 相关阅读:在阿里,我们如何管理代码分支 前言 阿里的许多实践看似简单,背后却蕴涵…

数据库_7_SQL基本操作——表操作

SQL基本操作——表操作 建表的过程就是声明列的过程。 表与字段是密不可分的。 一、新增数据表 create table [if not exists] 表名( 字段名字 数据类型, 字段名字 数据类型 -- 最后一行不需要逗号 )[表选项];if not exists:如果表名不存在,那么就创建,…

EXT.NET 更改lable和Text的颜色

2019独角兽企业重金招聘Python工程师标准>>> &#xfeff;&#xfeff; <ext:TextField ID"TextField1" " runat"server" FieldLabel"编号" LabelWidth"60" LabelAlign"Left" LabelStyle"color:red…

rest_framework08:分页器/根据ip进行频率限制

分页器 # 查询所有&#xff0c;才需要分页 from rest_framework.generics import ListAPIView# 内置三种分页方式 from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination,CursorPaginationPageNumberPaginationclass MyPageNumberPagination(Pag…

NYOJ746 整数划分

该题是一道区间DP的题目&#xff0c;做了几道区间DP&#xff0c;说起来高大上&#xff0c;也就是DP在区间内的形式而已&#xff0c;核心思想还是要想到转移->规划。 题意是在n位数中间加m个称号&#xff0c;使得最终乘积最大。 状态转移方程如下&#xff1a; dp[ i ][ j ]ma…

Spring MVC实现文件下载

方法一&#xff1a; RequestMapping("/testHttpMessageDown")public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {File file new File(request.getSession().getServletContext().getClassLoader().getResource("…

[MobX State Tree数据组件化开发][3]:选择正确的types.xxx

?系列文章目录? 定义Model时&#xff0c;需要正确地定义props中各字段的类型。本文将对MST提供的各种类型以及类型的工厂方法进行简单的介绍&#xff0c;方便同学们在定义props时挑选正确的类型。 前提 定义props之前&#xff0c;有一个前提是&#xff0c;你已经明确地知道这…

ubuntu系统备份和还原_如何使用Aptik在Ubuntu中备份和还原您的应用程序和PPA

ubuntu系统备份和还原If you need to reinstall Ubuntu or if you just want to install a new version from scratch, wouldn’t it be useful to have an easy way to reinstall all your apps and settings? You can easily accomplish this using a free tool called Apti…

rest_framework09:自动生成接口文档(简略)

coreapi 参考 python/Django-rest-framework框架/8-drf-自动生成接口文档 | Justin-刘清政的博客 Swagger 很多语言都支持&#xff0c;看起来用的人多。 参考fastapi的界面

AppDomainManager后门的实现思路

本文讲的是AppDomainManager后门的实现思路&#xff0c;0x00 前言从Casey SmithsubTee学到的一个技巧&#xff1a;针对.Net程序&#xff0c;通过修改AppDomainManager能够劫持.Net程序的启动过程。 如果劫持了系统常见.Net程序如powershell.exe的启动过程&#xff0c;向其添加…

所有内耗,都有解药。

你是否常常会有这种感觉&#xff1a;刚开始接手一件事情&#xff0c;脑海中已经幻想出无数个会发生的问题&#xff0c;心里也已笃定自己做不好&#xff1b;即使别人不经意的一句话&#xff0c;也会浮想一番&#xff0c;最终陷入自我怀疑&#xff1b;随便看到点什么&#xff0c;…

ABAP 通过sumbit调用另外一个程序使用job形式执行-简单例子

涉及到两个程序&#xff1a; ZTEST_ZUMA02 (主程序)ZTEST_ZUMA(被调用的程序&#xff0c;需要以后台job执行)"ztest_zuma 的代码DATA col TYPE i VALUE 0.DO 8 TIMES.MESSAGE JOB HERE TYPE S.ENDDO.程序ZTEST_ZUMA是在程序ZTEST_ZUMA02中以job的形式调用的&#xff0c;先…

那些影响深远的弯路

静儿最近反思很多事情&#xff0c;不仅是当时做错了。错误定式形成的思维习惯对自己的影响比事情本身要大的多。经常看到周围的同事&#xff0c;非常的羡慕。他们都很聪明、有自己的方法。就算有些同事工作经验相对少一些&#xff0c;但是就像在废墟上创建一个辉煌的城市要比在…

如何使用APTonCD备份和还原已安装的Ubuntu软件包

APTonCD is an easy way to back up your installed packages to a disc or ISO image. You can quickly restore the packages on another Ubuntu system without downloading anything. APTonCD是将安装的软件包备份到光盘或ISO映像的简便方法。 您可以在不下载任何东西的情况…

rest_framework10:base64补充/修改头像

base64补充 # base64 变长&#xff0c;可反解 # md5 固定长度&#xff0c;不可反解# base64 编码和解码 import base64 import json dic{name:test,age:18} dic_strjson.dumps(dic)retbase64.b64encode(dic_str.encode(utf-8)) print(ret)# 解码 ret2base64.b64decode(ret) pri…

next_permutation(全排列算法)

next_permutation(全排列算法) STL提供了两个用来计算排列组合关系的算法&#xff0c;分别是next_permutation和prev_permutation。 首先解释下全排列&#xff0c;顾名思义&#xff0c;即一组数的全部排列的情况。 next_permutation 即列出一组数的全部排列情况&#xff0c;不过…

C#自定义字符串压缩和解压缩源码库

如下的内容是关于C#自定义字符串压缩和解压缩库的内容。class ZipLib{public static string Zip(string value){byte[] byteArray new byte[value.Length];int indexBA 0;foreach (char item in value.ToCharArray()){byteArray[indexBA] (byte)item;}System.IO.MemoryStrea…

使用 Visual Studio 2022 调试Dapr 应用程序

使用Dapr 编写的是一个多进程的程序, 两个进程之间依赖于启动顺序来组成父子进程&#xff0c;使用Visual Studio 调试起来可能会比较困难&#xff0c;因为 Visual Studio 默认只会把你当前设置的启动项目的启动调试。好在有Visual Studio 扩展&#xff08;Microsoft Child Proc…

卸载 cube ui_如何还原Windows 8附带的已卸载现代UI应用程序

卸载 cube uiWindows 8 ships with built-in apps available on the Modern UI screen (formerly the Metro or Start screen), such as Mail, Calendar, Photos, Music, Maps, and Weather. Installing additional Modern UI apps is easy using the Windows Store, and unins…

rest_framework11:jwt简单例子/自定制基于jwt认证类

jwt简单例子 一、登陆设置 1.不需要写login的视图类&#xff0c;使用jwt内置的。 2.需要前置条件&#xff0c;已有继承AbstractUser models,并且有数据&#xff0c;用于校验&#xff0c;返回token。 urls.py from rest_framework_jwt.views import obtain_jwt_tokenurlpat…