侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Django rest framework工具包简单用法示例

框架(架构)  /  管理员 发布于 7年前   222

本文实例讲述了Django rest framework工具包简单用法。分享给大家供大家参考,具体如下:

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

下面简单说一下几个功能的实现方法。

实现功能为,匿名用户访问首页一分钟能访问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路径最好使用名词。我们这里注册三个视图函数的url,实现验证,首页和定单页面。

from django.conf.urls import urlfrom django.contrib import adminfrom app import viewsurlpatterns = [  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文件设置路由

第三步,auth视图函数

from rest_framework.views import APIViewfrom rest_framework.request import Requestfrom django.http import JsonResponse,HttpResponsefrom app.utils.commons import gen_tokenfrom app.utils.auth import LuffyAuthenticationfrom app.utils.throttle import LuffyAnonRateThrottle,LuffyUserRateThrottlefrom app.utils.permission import LuffyPermissionfrom . import modelsclass AuthView(APIView):  """  认证相关视图  由于继承了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已经不是原来的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})      # 数据库存入一个token信息      ret['code'] = 1001      ret['token'] = tk    else:      ret['msg'] = "用户名或密码错误"    return JsonResponse(ret)

上面的代码主要是实现了一个验证的功能,通过gen_token函数来验证,并存入数据库信息。

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

通过时间和哈希等生成一个不重复的字符串。

第四步,index视图函数

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]  #访问次数限制,如果合格都为True  def get(self,request,*args,**kwargs):    return HttpResponse('首页')

同样,将LuffyAuthentication,LuffyAnonRateThrottle,LuffyUserRateThrottle写到了utils目录下。代码如下:

auth.py :

from rest_framework.authentication import BaseAuthenticationfrom rest_framework import exceptionsfrom app import modelsclass 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信息存到数据库

throttle.py :

from rest_framework.throttling import BaseThrottle,SimpleRateThrottleclass 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    # 获取当前访问用户的唯一标识    self.key = self.get_cache_key(request, view)    # 根据当前用户的唯一标识,获取所有访问记录    # [1511312683.7824545, 1511312682.7824545, 1511312681.7824545]    self.history = self.cache.get(self.key, [])    # 获取当前时间    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:  #判断访问次数是否大于限制次数      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    # 获取当前访问用户的唯一标识    # 用户对所有页面    # self.key = request.user.user    self.key = request.user.user + view.__class__.__name__    # 用户对单页面的访问限制    # 根据当前用户的唯一标识,获取所有访问记录    # [1511312683.7824545, 1511312682.7824545, 1511312681.7824545]    self.history = self.cache.get(self.key, [])    # 获取当前时间    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:  #访问次数的限制      return self.throttle_failure()    return self.throttle_success()  #返回True

限制匿名用户和登录用户的访问次数,需要从settings中的配置拿去配置信息。

permission.py

from rest_framework.permissions import BasePermissionclass LuffyPermission(BasePermission):  def has_permission(self, request, view):    """    Return `True` if permission is granted, `False` otherwise.    """    if request.user:      return True    return False

权限控制

第五步,order视图函数

class OrderView(APIView):  """  订单页面:只有登录成功后才能访问    - 认证(匿名和用户)    - 权限(用户)    - 限制()  """  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次  },}

最后,实现功能为,匿名用户访问首页一分钟能访问3次,登录用户一分钟访问6次,只有登录用户才能访问order页面。

学习Django rest framework需要随时查看源代码,判断源代码的逻辑思路来自定义自己的功能,如此学习效率极高。

希望本文所述对大家基于Django框架的Python程序设计有所帮助。


  • 上一条:
    Django中的文件的上传的几种方式
    下一条:
    Django 中使用流响应处理视频的方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Filament v3.1版本发布(0个评论)
    • docker + gitea搭建一个git服务器流程步骤(0个评论)
    • websocket的三种架构方式使用优缺点浅析(0个评论)
    • ubuntu20.4系统中宿主机安装nginx服务,docker容器中安装php8.2实现运行laravel10框架网站(0个评论)
    • phpstudy_pro(小皮面板)中安装最新php8.2.9版本流程步骤(0个评论)
    • 近期文章
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2018-05
    • 2020-02
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-11
    • 2021-03
    • 2021-09
    • 2021-10
    • 2021-11
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-08
    • 2023-08
    • 2023-10
    • 2023-12
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客