rest_framework06:自動生成路由\action使用\認證

自動生成路由

# 1.導入routers模塊
from rest_framework import routers# 2.實例化類
router=routers.SimpleRouter()# 3.注冊
# ('前綴','繼承自ModelViewSet視圖類','別名')
router.register('books7',views.BooksView) # 不要加斜杠# 4.加入
urlpatterns+=router.urls

action使用

裝時期,給ModelViewSet的試圖類,自定義函數,以及路由。

# action 用法
from rest_framework.decorators import action
class BookViewSet(ModelViewSet):queryset = Book.objects.all()serializer_class = BookModelSerializer# methods 第一個參數,傳一個列表,列表中放請求方式# ‘/books/get_1’ 是請求地址。books是ModelViewSet 注冊的路由# detal:True是, 帶pk ,即/books/1/get_1@action(methods=['GET','POST'],detail=False)def get_1(self,request):book=self.get_queryset()[:2]ser=self.get_serializer(book,many=True)return Response(ser.data)

認證

局部認證

1.新寫認證類

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from app01.models import UserTokenclass MyAuthentication(BaseAuthentication):def authenticate(self, request):# 認證邏輯, 如果認證通過,返回兩個值# 如果認證失敗,拋出AuthenticationFailed異常token=request.GET.get('token')if token:user_token=UserToken.objects.filter(token=token).first()if user_token:return user_token.user,tokenelse:raise AuthenticationFailed('認證失敗')else:raise AuthenticationFailed('請求地址需要帶token')

2.認證邏輯,如使用token,數據庫儲存。

models.py

class User(models.Model):username=models.CharField(max_length=32)password=models.CharField(max_length=32)user_type=models.IntegerField(choices=((1,'超級用戶'),(2,'普通用戶'),(3,'二筆用戶')))class UserToken(models.Model):token=models.CharField(max_length=64)user=models.OneToOneField(to=User,on_delete=models.CASCADE)

views.py

登錄功能

# 認證功能
from app01 import models
import uuidclass LoginView(APIView):def post(self,request):myRespone=MyResponse()username=request.data.get('username')password=request.data.get('password')print(username,password)user=models.User.objects.filter(username=username,password=password).first()if user:# 登陸成功,生成一個隨機及付出token=uuid.uuid4()# 查詢,沒有就新增models.UserToken.objects.update_or_create(defaults={'token':token},user=user)myRespone.msg='登陸成功'myRespone.token=tokenelse:myRespone.status=101myRespone.msg='用戶名或密碼錯誤'return Response(myRespone.get_dic)

視圖類

增加authentication_classes

from rest_framework.viewsets import ViewSetMixinfrom app01.app_auth import MyAuthentication
# ViewSetMixin一定放在前面,重寫as_view方法
class Books6View(ViewSetMixin,GenericAPIView):authentication_classes = [MyAuthentication]def get_all_book(self,request):books = Book.objects.all()book_ser = BookSerializer(books, many=True)return Response(book_ser.data)

全局認證

settings.py

REST_FRAMEWORK={"DEFAULT_AUTHENTICATION_CLASSES":["app01.app_auth.MyAuthentication",]
}

登錄視圖類需要排除認證,在類里寫空列表

authentication_classes = []

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/280432.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/280432.shtml
英文地址,請注明出處:http://en.pswp.cn/news/280432.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

char data[0]在struct末尾的用法

在實際的編程中,我們經常需要使用變長數組,但是C語言并不支持變長的數組。此時,我們可以使用結構體的方法實現C語言變長數組。 struct MyData { int nLen; char data[0];}; 在結構中,data是一個數組名;但該數組沒有元素…

使用Java實現K-Means聚類算法

2019獨角獸企業重金招聘Python工程師標準>>> 關于K-Means介紹很多,還不清楚可以查一些相關資料。 個人對其實現步驟簡單總結為4步: 1.選出k值,隨機出k個起始質心點。 2.分別計算每個點和k個起始質點之間的距離,就近歸類。 3.最終中心點集可以劃分為…

在PowerShell中顯示高級進度條

如果你需要編寫一些PowerShell腳本,尤其在處理一些相對復雜的任務時,你可能希望添加進度條的功能,以便隨時可以了解進展情況。Write-Progress 這個命令可以幫助你完成簡單的需求,請參考官方文檔即可,但下圖一個示例&am…

當檢測到運動時如何自動打開門燈

If it’s dark out and someone comes to your door, you probably can’t see them unless your porch light is on. Furthermore, if a potential burglar approaches your front door, a motion light can help scare them away. 如果天黑了,有人進了您的門&…

分布式系統的那些事兒(六) - SOA架構體系

有十來天沒發文了,實在抱歉!最近忙著錄視頻,同時也做了個開源的后臺管理系統LeeCX,目前比較簡單,但是后續會把各類技術完善。具體可以點擊“原文鏈接”。 那么今天繼續說分布式系統的那些事。 我們現在動不動就講分布式…

rest_framework07:權限/頻率/過濾組件/排序/異常處理封裝Response對象

權限 寫一個類,繼承BasePermission,如果通過返回True,否則False 這里需要配合認證使用,否則沒有user_type屬性。 from rest_framework.permissions import BasePermissionclass UserPermission(BasePermission):def has_permis…

在阿里,我們如何管理測試環境

為什么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映像的簡便方法。 您可以在不下載任何東西的情況…