本文實(shí)例講述了Django rest framework工具包簡(jiǎn)單用法。分享給大家供大家參考,具體如下:
Django rest framework 工具包做API非常方便。
下面簡(jiǎn)單說(shuō)一下幾個(gè)功能的實(shí)現(xiàn)方法。
實(shí)現(xiàn)功能為,匿名用戶訪問(wèn)首頁(yè)一分鐘能訪問(wèn)3次,登錄用戶一分鐘訪問(wèn)6次,只有登錄用戶才能訪問(wèn)order頁(yè)面。
第一步,注冊(cè)app
1
2
3
4
5
6
7
8
9
10
|
INSTALLED_APPS = [ 'django.contrib.admin' , 'django.contrib.auth' , 'django.contrib.contenttypes' , 'django.contrib.sessions' , 'django.contrib.messages' , 'django.contrib.staticfiles' , 'app.apps.AppConfig' , 'rest_framework' , #注冊(cè) ] |
settings文件注冊(cè)app
第二步,定義URL,注意url路徑最好使用名詞。我們這里注冊(cè)三個(gè)視圖函數(shù)的url,實(shí)現(xiàn)驗(yàn)證,首頁(yè)和定單頁(yè)面。
1
2
3
4
5
6
7
8
9
|
from django.conf.urls import url from django.contrib import admin from app import views urlpatterns = [ url(r '^admin/' , admin.site.urls), url(r '^auth/' , views.AuthView.as_view()), #驗(yàn)證 url(r '^index/' , views.IndexView.as_view()), #首頁(yè) url(r '^order/' , views.OrderView.as_view()), #定單 ] |
url文件設(shè)置路由
第三步,auth視圖函數(shù)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
from rest_framework.views import APIView from rest_framework.request import Request from django.http import JsonResponse,HttpResponse from app.utils.commons import gen_token from app.utils.auth import LuffyAuthentication from app.utils.throttle import LuffyAnonRateThrottle,LuffyUserRateThrottle from app.utils.permission import LuffyPermission from . import models class AuthView(APIView): """ 認(rèn)證相關(guān)視圖 由于繼承了APIView,所以csrf就沒(méi)有了,具體的源代碼只是有一個(gè)裝飾器, 加上了csrf_exempt裝飾器,屏蔽了csrf 寫(xiě)法是在return的時(shí)候csrf_exempt(view) 和@使用裝飾器效果是一樣的,這種寫(xiě)法還可以寫(xiě)在url路由中。 """ def post( self ,request, * args, * * kwargs): """ 用戶登錄功能 :param request: :param args: :param kwargs: :return: """ ret = { 'code' : 1000 , 'msg' : None } # 默認(rèn)要返回的信息 user = request.data.get( 'username' ) # 這里的request已經(jīng)不是原來(lái)的request了 pwd = request.data.get( 'password' ) user_obj = models.UserInfo.objects. filter (user = user, pwd = pwd).first() if user_obj: tk = gen_token(user) #返回一個(gè)哈希過(guò)得字符串 #進(jìn)行token驗(yàn)證 models.Token.objects.update_or_create(user = user_obj, defaults = { 'token' : tk}) # 數(shù)據(jù)庫(kù)存入一個(gè)token信息 ret[ 'code' ] = 1001 ret[ 'token' ] = tk else : ret[ 'msg' ] = "用戶名或密碼錯(cuò)誤" return JsonResponse(ret) |
上面的代碼主要是實(shí)現(xiàn)了一個(gè)驗(yàn)證的功能,通過(guò)gen_token
函數(shù)來(lái)驗(yàn)證,并存入數(shù)據(jù)庫(kù)信息。
gen_token
單獨(dú)寫(xiě)到一個(gè)utils目錄下的auth.py文件中。代碼如下:
1
2
3
4
5
6
7
|
def gen_token(username): import time import hashlib ctime = str (time.time()) hash = hashlib.md5(username.encode( 'utf-8' )) hash .update(ctime.encode( 'utf-8' )) return hash .hexdigest() |
通過(guò)時(shí)間和哈希等生成一個(gè)不重復(fù)的字符串。
第四步,index視圖函數(shù)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class IndexView(APIView): """ 用戶認(rèn)證 http://127.0.0.1:8001/v1/index/?tk=sdfasdfasdfasdfasdfasdf 獲取用戶傳入的Token 首頁(yè)限制:request.user 匿名:5/m 用戶:10/m """ authentication_classes = [LuffyAuthentication,] #認(rèn)證成功返回一個(gè)用戶名,一個(gè)對(duì)象,不成功就是None throttle_classes = [LuffyAnonRateThrottle,LuffyUserRateThrottle] #訪問(wèn)次數(shù)限制,如果合格都為True def get( self ,request, * args, * * kwargs): return HttpResponse( '首頁(yè)' ) |
同樣,將LuffyAuthentication,LuffyAnonRateThrottle,LuffyUserRateThrottle寫(xiě)到了utils目錄下。代碼如下:
auth.py :
1
2
3
4
5
6
7
8
9
10
11
12
13
|
from rest_framework.authentication import BaseAuthentication from rest_framework import exceptions from app import models class LuffyAuthentication(BaseAuthentication): def authenticate( self , request): tk = request.query_params.get( 'tk' ) if not tk: return ( None , None ) # raise exceptions.AuthenticationFailed('認(rèn)證失敗') token_obj = models.Token.objects. filter (token = tk).first() if not token_obj: return ( None , None ) return (token_obj.user,token_obj) |
驗(yàn)證是否為登錄用戶,如果之前沒(méi)有登陸過(guò),則將token信息存到數(shù)據(jù)庫(kù)
throttle.py :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
from rest_framework.throttling import BaseThrottle,SimpleRateThrottle class LuffyAnonRateThrottle(SimpleRateThrottle): scope = "luffy_anon" def allow_request( self , request, view): """ Return `True` if the request should be allowed, `False` otherwise. """ if request.user: return True # 獲取當(dāng)前訪問(wèn)用戶的唯一標(biāo)識(shí) self .key = self .get_cache_key(request, view) # 根據(jù)當(dāng)前用戶的唯一標(biāo)識(shí),獲取所有訪問(wèn)記錄 # [1511312683.7824545, 1511312682.7824545, 1511312681.7824545] self .history = self .cache.get( self .key, []) # 獲取當(dāng)前時(shí)間 self .now = self .timer() # Drop any requests from the history which have now passed the # throttle duration while self .history and self .history[ - 1 ] < = self .now - self .duration: self .history.pop() if len ( self .history) > = self .num_requests: #判斷訪問(wèn)次數(shù)是否大于限制次數(shù) return self .throttle_failure() return self .throttle_success() #返回True def get_cache_key( self , request, view): return 'throttle_%(scope)s_%(ident)s' % { 'scope' : self .scope, 'ident' : self .get_ident(request), # 判斷是否為代理等等 } class LuffyUserRateThrottle(SimpleRateThrottle): scope = "luffy_user" def allow_request( self , request, view): """ Return `True` if the request should be allowed, `False` otherwise. """ if not request.user: #判斷登錄直接返回True return True # 獲取當(dāng)前訪問(wèn)用戶的唯一標(biāo)識(shí) # 用戶對(duì)所有頁(yè)面 # self.key = request.user.user self .key = request.user.user + view.__class__.__name__ # 用戶對(duì)單頁(yè)面的訪問(wèn)限制 # 根據(jù)當(dāng)前用戶的唯一標(biāo)識(shí),獲取所有訪問(wèn)記錄 # [1511312683.7824545, 1511312682.7824545, 1511312681.7824545] self .history = self .cache.get( self .key, []) # 獲取當(dāng)前時(shí)間 self .now = self .timer() # Drop any requests from the history which have now passed the # throttle duration while self .history and self .history[ - 1 ] < = self .now - self .duration: self .history.pop() if len ( self .history) > = self .num_requests: #訪問(wèn)次數(shù)的限制 return self .throttle_failure() return self .throttle_success() #返回True |
限制匿名用戶和登錄用戶的訪問(wèn)次數(shù),需要從settings中的配置拿去配置信息。
permission.py
1
2
3
4
5
6
7
8
9
|
from rest_framework.permissions import BasePermission class LuffyPermission(BasePermission): def has_permission( self , request, view): """ Return `True` if permission is granted, `False` otherwise. """ if request.user: return True return False |
權(quán)限控制
第五步,order視圖函數(shù)
1
2
3
4
5
6
7
8
9
10
11
12
|
class OrderView(APIView): """ 訂單頁(yè)面:只有登錄成功后才能訪問(wèn) - 認(rèn)證(匿名和用戶) - 權(quán)限(用戶) - 限制() """ authentication_classes = [LuffyAuthentication, ] permission_classes = [LuffyPermission,] #登錄就返回True throttle_classes = [LuffyAnonRateThrottle, LuffyUserRateThrottle] def get( self ,request, * args, * * kwargs): return HttpResponse( '訂單' ) |
第六步,settings配置
1
2
3
4
5
6
7
8
|
REST_FRAMEWORK = { 'UNAUTHENTICATED_USER' : None , 'UNAUTHENTICATED_TOKEN' : None , "DEFAULT_THROTTLE_RATES" : { 'luffy_anon' : '3/m' , #匿名用戶一分鐘訪問(wèn)3次 'luffy_user' : '6/m' #登錄用戶一分鐘訪問(wèn)6次 }, } |
最后,實(shí)現(xiàn)功能為,匿名用戶訪問(wèn)首頁(yè)一分鐘能訪問(wèn)3次,登錄用戶一分鐘訪問(wèn)6次,只有登錄用戶才能訪問(wèn)order頁(yè)面。
學(xué)習(xí)Django rest framework需要隨時(shí)查看源代碼,判斷源代碼的邏輯思路來(lái)自定義自己的功能,如此學(xué)習(xí)效率極高。
希望本文所述對(duì)大家基于Django框架的Python程序設(shè)計(jì)有所幫助。
原文鏈接:https://www.cnblogs.com/ArmoredTitan/p/7882272.html