最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Django rest framework工具包簡單用法示例

 更新時間:2018年07月20日 10:11:11   作者:鎧甲巨人  
這篇文章主要介紹了Django rest framework工具包簡單用法,結(jié)合匿名訪問控制的具體實例分析了Django rest framework工具包的注冊、路由設(shè)置、視圖、權(quán)限控制、配置等相關(guān)操作技巧,需要的朋友可以參考下

本文實例講述了Django rest framework工具包簡單用法。分享給大家供大家參考,具體如下:

Django rest framework 工具包做API非常方便。

下面簡單說一下幾個功能的實現(xiàn)方法。

實現(xiàn)功能為,匿名用戶訪問首頁一分鐘能訪問3次,登錄用戶一分鐘訪問6次,只有登錄用戶才能訪問order頁面。

第一步,注冊app

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', #注冊
]

settings文件注冊app

第二步,定義URL,注意url路徑最好使用名詞。我們這里注冊三個視圖函數(shù)的url,實現(xiàn)驗證,首頁和定單頁面。

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()), #驗證
  url(r'^index/', views.IndexView.as_view()), #首頁
  url(r'^order/', views.OrderView.as_view()), #定單
]

url文件設(shè)置路由

第三步,auth視圖函數(shù)

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):
  """
  認證相關(guān)視圖
  由于繼承了APIView,所以csrf就沒有了,具體的源代碼只是有一個裝飾器,
  加上了csrf_exempt裝飾器,屏蔽了csrf
  寫法是在return的時候csrf_exempt(view) 和@使用裝飾器效果是一樣的,這種寫法還可以寫在url路由中。
  """
  def post(self,request,*args,**kwargs):
    """
    用戶登錄功能
    :param request:
    :param args:
    :param kwargs:
    :return:
    """
    ret = {'code': 1000, 'msg': None}
    # 默認要返回的信息
    user = request.data.get('username')
    # 這里的request已經(jīng)不是原來的request了
    pwd = request.data.get('password')
    user_obj = models.UserInfo.objects.filter(user=user, pwd=pwd).first()
    if user_obj:
      tk = gen_token(user) #返回一個哈希過得字符串
      #進行token驗證
      models.Token.objects.update_or_create(user=user_obj, defaults={'token': tk})
      # 數(shù)據(jù)庫存入一個token信息
      ret['code'] = 1001
      ret['token'] = tk
    else:
      ret['msg'] = "用戶名或密碼錯誤"
    return JsonResponse(ret)

上面的代碼主要是實現(xiàn)了一個驗證的功能,通過gen_token函數(shù)來驗證,并存入數(shù)據(jù)庫信息。

gen_token單獨寫到一個utils目錄下的auth.py文件中。代碼如下:

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()

通過時間和哈希等生成一個不重復(fù)的字符串。

第四步,index視圖函數(shù)

class IndexView(APIView):
  """
  用戶認證
    http://127.0.0.1:8001/v1/index/?tk=sdfasdfasdfasdfasdfasdf
    獲取用戶傳入的Token
  首頁限制:request.user
    匿名:5/m
    用戶:10/m
  """
  authentication_classes = [LuffyAuthentication,]
  #認證成功返回一個用戶名,一個對象,不成功就是None
  throttle_classes = [LuffyAnonRateThrottle,LuffyUserRateThrottle]
  #訪問次數(shù)限制,如果合格都為True
  def get(self,request,*args,**kwargs):
    return HttpResponse('首頁')

同樣,將LuffyAuthentication,LuffyAnonRateThrottle,LuffyUserRateThrottle寫到了utils目錄下。代碼如下:

auth.py :

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('認證失敗')
    token_obj = models.Token.objects.filter(token=tk).first()
    if not token_obj:
      return (None,None)
    return (token_obj.user,token_obj)

驗證是否為登錄用戶,如果之前沒有登陸過,則將token信息存到數(shù)據(jù)庫

throttle.py :

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)前訪問用戶的唯一標(biāo)識
    self.key = self.get_cache_key(request, view)
    # 根據(jù)當(dāng)前用戶的唯一標(biāo)識,獲取所有訪問記錄
    # [1511312683.7824545, 1511312682.7824545, 1511312681.7824545]
    self.history = self.cache.get(self.key, [])
    # 獲取當(dāng)前時間
    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:  #判斷訪問次數(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)前訪問用戶的唯一標(biāo)識
    # 用戶對所有頁面
    # self.key = request.user.user
    self.key = request.user.user + view.__class__.__name__
    # 用戶對單頁面的訪問限制
    # 根據(jù)當(dāng)前用戶的唯一標(biāo)識,獲取所有訪問記錄
    # [1511312683.7824545, 1511312682.7824545, 1511312681.7824545]
    self.history = self.cache.get(self.key, [])
    # 獲取當(dāng)前時間
    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:  #訪問次數(shù)的限制
      return self.throttle_failure()
    return self.throttle_success()  #返回True

限制匿名用戶和登錄用戶的訪問次數(shù),需要從settings中的配置拿去配置信息。

permission.py

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ù)

class OrderView(APIView):
  """
  訂單頁面:只有登錄成功后才能訪問
    - 認證(匿名和用戶)
    - 權(quán)限(用戶)
    - 限制()
  """
  authentication_classes = [LuffyAuthentication, ]
  permission_classes = [LuffyPermission,] #登錄就返回True
  throttle_classes = [LuffyAnonRateThrottle, LuffyUserRateThrottle]
  def get(self,request,*args,**kwargs):
    return HttpResponse('訂單')

第六步,settings配置

REST_FRAMEWORK = {
  'UNAUTHENTICATED_USER': None,
  'UNAUTHENTICATED_TOKEN': None,
  "DEFAULT_THROTTLE_RATES": {
    'luffy_anon': '3/m', #匿名用戶一分鐘訪問3次
    'luffy_user': '6/m'  #登錄用戶一分鐘訪問6次
  },
}

最后,實現(xiàn)功能為,匿名用戶訪問首頁一分鐘能訪問3次,登錄用戶一分鐘訪問6次,只有登錄用戶才能訪問order頁面。

學(xué)習(xí)Django rest framework需要隨時查看源代碼,判斷源代碼的邏輯思路來自定義自己的功能,如此學(xué)習(xí)效率極高。

希望本文所述對大家基于Django框架的Python程序設(shè)計有所幫助。

相關(guān)文章

  • Python強化練習(xí)之Tensorflow2 opp算法實現(xiàn)月球登陸器

    Python強化練習(xí)之Tensorflow2 opp算法實現(xiàn)月球登陸器

    在面向?qū)ο蟪霈F(xiàn)之前,我們采用的開發(fā)方法都是面向過程的編程(OPP)。面向過程的編程中最常用的一個分析方法是“功能分解”。我們會把用戶需求先分解成模塊,然后把模塊分解成大的功能,再把大的功能分解成小的功能,整個需求就是按照這樣的方式,最終分解成一個一個的函數(shù)
    2021-10-10
  • 解決PyCharm無法使用lxml庫的問題(圖解)

    解決PyCharm無法使用lxml庫的問題(圖解)

    這篇文章主要介紹了解決PyCharm無法使用lxml庫的問題,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-12-12
  • Python處理excel根據(jù)全稱自動填寫簡稱

    Python處理excel根據(jù)全稱自動填寫簡稱

    這篇文章主要為大家詳細介紹了Python處理excel根據(jù)全稱自動填寫簡稱,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-03-03
  • 詳解PyQt5中textBrowser顯示print語句輸出的簡單方法

    詳解PyQt5中textBrowser顯示print語句輸出的簡單方法

    這篇文章主要介紹了詳解PyQt5中textBrowser顯示print語句輸出的簡單方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • Django的多表查詢操作實戰(zhàn)

    Django的多表查詢操作實戰(zhàn)

    Django提供一種強大而又直觀的方式來"處理"查詢中的關(guān)聯(lián)關(guān)系,它在后臺自動幫你處理JOIN,下面這篇文章主要給大家介紹了關(guān)于Django多表查詢操作的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2023-06-06
  • python常見字符串處理函數(shù)與用法匯總

    python常見字符串處理函數(shù)與用法匯總

    這篇文章主要介紹了python常見字符串處理函數(shù)與用法,結(jié)合實例形式詳細分析了Python字符串操作函數(shù)find、join、replace及split功能、使用技巧與操作注意事項,需要的朋友可以參考下
    2019-10-10
  • python人工智能遺傳算法示例解析

    python人工智能遺傳算法示例解析

    這篇文章主要為大家介紹了python人工智能遺傳算法示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-05-05
  • 解決Python串口接收無標(biāo)識不定長數(shù)據(jù)

    解決Python串口接收無標(biāo)識不定長數(shù)據(jù)

    這篇文章主要介紹了解決Python串口接收無標(biāo)識不定長數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • python遍歷小寫英文字母的方法

    python遍歷小寫英文字母的方法

    今天小編就為大家分享一篇python遍歷小寫英文字母的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • 解決Python中的modf()函數(shù)取小數(shù)部分不準(zhǔn)確問題

    解決Python中的modf()函數(shù)取小數(shù)部分不準(zhǔn)確問題

    這篇文章主要介紹了解決Python中的modf()函數(shù)取小數(shù)部分不準(zhǔn)確問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-05-05

最新評論

鄂州市| 永济市| 新建县| 天津市| 临猗县| 夹江县| 阿拉善右旗| 辰溪县| 沂南县| 浮山县| 宜丰县| 临邑县| 日土县| 克拉玛依市| 乌恰县| 积石山| 阿巴嘎旗| 南岸区| 兴宁市| 唐海县| 泰兴市| 克什克腾旗| 临沭县| 靖宇县| 辽中县| 永安市| 秦皇岛市| 晋城| 定结县| 浪卡子县| 昭通市| 昌乐县| 紫阳县| 英山县| 新建县| 满城县| 白玉县| 承德市| 金乡县| 淄博市| 彭州市|