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.pswp.cn/news/280426.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/280426.shtml
英文地址,請注明出處:http://en.pswp.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…