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


Posted in Python onJuly 20, 2018

本文实例讲述了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 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文件设置路由

第三步,auth视图函数

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):
  """
  认证相关视图
  由于继承了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 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信息存到数据库

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
    # 获取当前访问用户的唯一标识
    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 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

权限控制

第五步,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程序设计有所帮助。

Python 相关文章推荐
Python3实现将文件归档到zip文件及从zip文件中读取数据的方法
May 22 Python
python选择排序算法实例总结
Jul 01 Python
Django中模版的子目录与include标签的使用方法
Jul 16 Python
在Python的Django框架中生成CSV文件的方法
Jul 22 Python
Python网络编程之TCP套接字简单用法示例
Apr 09 Python
Anaconda 离线安装 python 包的操作方法
Jun 11 Python
删除DataFrame中值全为NaN或者包含有NaN的列或行方法
Nov 06 Python
Python unittest 简单实现参数化的方法
Nov 30 Python
解决vscode python print 输出窗口中文乱码的问题
Dec 03 Python
django 2.2和mysql使用的常见问题
Jul 18 Python
python解释器pycharm安装及环境变量配置教程图文详解
Feb 26 Python
python绘制雷达图实例讲解
Jan 03 Python
Django 中使用流响应处理视频的方法
Jul 20 #Python
Python实现手写一个类似django的web框架示例
Jul 20 #Python
python 实现求解字符串集的最长公共前缀方法
Jul 20 #Python
python实现求两个字符串的最长公共子串方法
Jul 20 #Python
Django基础知识与基本应用入门教程
Jul 20 #Python
opencv python 2D直方图的示例代码
Jul 20 #Python
Linux下python制作名片示例
Jul 20 #Python
You might like
DedeCMS dede_channeltype表字段注释
2010/04/07 PHP
PHP 计算代码执行耗时的代码修正网上普遍错误
2011/05/14 PHP
PHP面向对象三大特点学习(充分理解抽象、封装、继承、多态)
2012/05/07 PHP
ThinkPHP使用心得分享-上传类UploadFile的使用
2014/05/15 PHP
php+js实现异步图片上传实例分享
2014/06/02 PHP
基于PHP实现商品成交时发送短信功能
2016/05/11 PHP
PHP正则+Snoopy抓取框架实现的抓取淘宝店信誉功能实例
2017/05/17 PHP
关于锚点跳转及jQuery下相关操作与插件
2012/10/01 Javascript
Node.js 日志处理模块log4js
2016/08/28 Javascript
js编写三级联动简单案例
2016/12/21 Javascript
javaScript产生随机数的用法小结
2018/04/21 Javascript
js限制输入框只能输入数字(onkeyup触发)
2018/09/28 Javascript
mpvue微信小程序多列选择器用法之省份城市选择的实现
2019/03/07 Javascript
vue学习笔记之给组件绑定原生事件操作示例
2020/02/27 Javascript
实例讲解Python中的私有属性
2014/08/21 Python
python pandas中对Series数据进行轴向连接的实例
2018/06/08 Python
Python 查找list中的某个元素的所有的下标方法
2018/06/27 Python
python 常用的基础函数
2018/07/10 Python
使用GitHub和Python实现持续部署的方法
2019/05/09 Python
python 使用turtule绘制递归图形(螺旋、二叉树、谢尔宾斯基三角形)
2019/05/30 Python
Django用户认证系统 Web请求中的认证解析
2019/08/02 Python
详解Selenium 元素定位和WebDriver常用方法
2020/12/04 Python
python 如何把docker-compose.yaml导入到数据库相关条目里
2021/01/15 Python
浅析HTML5中的 History 模式
2017/06/22 HTML / CSS
巴西最大的家电和百货零售商:Casas Bahia
2016/11/22 全球购物
德国知名健康零食网上商店:Seeberger
2017/07/27 全球购物
英国花园药房: The Garden Pharmacy
2017/12/28 全球购物
编写一个 C 函数,该函数在一个字符串中找到可能的最长的子字符串,且该字符串是由同一字符组成的
2015/07/23 面试题
面试后的英文感谢信
2014/02/01 职场文书
小学生开学感言
2014/02/28 职场文书
公证委托书模板
2014/04/03 职场文书
欢迎词范文
2015/01/27 职场文书
2015高考寄语集锦
2015/02/27 职场文书
Python 使用dict实现switch的操作
2021/04/07 Python
使用pytorch实现线性回归
2021/04/11 Python
vue项目打包后路由错误的解决方法
2022/04/13 Vue.js