Django 限制访问频率的思路详解


Posted in Python onDecember 24, 2019

最近做了一个系统由于部分接口需要进行耗时操作,因而不希望用户进行频繁访问,需要进行访问频率限制。如果要自己实现一个访问限制功能相对来说也不会太复杂,并且网上有各种代码可以参考。如果自己不想实现这个代码可以使用 Django Ratelimit 。

Django Ratelimit is a ratelimiting decorator for Django views.
https://travis-ci.org/jsocol/django-ratelimit.png?branch=master Code: https://github.com/jsocol/django-ratelimit License: Apache Software License Issues: https://github.com/jsocol/django-ratelimit/issues Documentation: http://django-ratelimit.readthedocs.org/

使用方法也相对来说比较简单:

@ratelimit(key='ip', rate='5/m')
def myview(request):
  # Will be true if the same IP makes more than 5 POST
  # requests/minute.
  was_limited = getattr(request, 'limited', False)
  return HttpResponse()
@ratelimit(key='ip', rate='5/m', block=True)
def myview(request):
  # If the same IP makes >5 reqs/min, will raise Ratelimited
  return HttpResponse()
@ratelimit(key='post:username', rate='5/m', method=['GET', 'POST'])
def login(request):
  # If the same username is used >5 times/min, this will be True.
  # The `username` value will come from GET or POST, determined by the
  # request method.
  was_limited = getattr(request, 'limited', False)
  return HttpResponse()
@ratelimit(key='post:username', rate='5/m')
@ratelimit(key='post:tenant', rate='5/m')
def login(request):
  # Use multiple keys by stacking decorators.
  return HttpResponse()
@ratelimit(key='get:q', rate='5/m')
@ratelimit(key='post:q', rate='5/m')
def search(request):
  # These two decorators combine to form one rate limit: the same search
  # query can only be tried 5 times a minute, regardless of the request
  # method (GET or POST)
  return HttpResponse()
@ratelimit(key='ip', rate='4/h')
def slow(request):
  # Allow 4 reqs/hour.
  return HttpResponse()
rate = lambda r: None if request.user.is_authenticated else '100/h'
@ratelimit(key='ip', rate=rate)
def skipif1(request):
  # Only rate limit anonymous requests
  return HttpResponse()
@ratelimit(key='user_or_ip', rate='10/s')
@ratelimit(key='user_or_ip', rate='100/m')
def burst_limit(request):
  # Implement a separate burst limit.
  return HttpResponse()
@ratelimit(group='expensive', key='user_or_ip', rate='10/h')
def expensive_view_a(request):
  return something_expensive()
@ratelimit(group='expensive', key='user_or_ip', rate='10/h')
def expensive_view_b(request):
  # Shares a counter with expensive_view_a
  return something_else_expensive()
@ratelimit(key='header:x-cluster-client-ip')
def post(request):
  # Uses the X-Cluster-Client-IP header value.
  return HttpResponse()
@ratelimit(key=lambda r: r.META.get('HTTP_X_CLUSTER_CLIENT_IP',
                  r.META['REMOTE_ADDR'])
def myview(request):
  # Use `X-Cluster-Client-IP` but fall back to REMOTE_ADDR.
  return HttpResponse()

不过需要注意如果和django rest framwork一起使用的话,要将Ratelimit 装饰器放到第一行,如下:

@ratelimit(key='user', rate='1/3s', block=True, method=ratelimit.ALL)
@api_view(['POST', 'GET'])
@csrf_exempt
def api_get_level(request):

否则会导致如下的错误信息:

IndexError at /rest-api/level/
tuple index out of range
Request Method: GET
Request URL: http://192.168.1.195:8006/rest-api/level/
Django Version: 2.2.7
Exception Type: IndexError
Exception Value: 
tuple index out of range
Exception Location: F:\PyCharmProjects\server\venv\lib\site-packages\ratelimit\decorators.py in _wrapped, line 23
Python Executable: F:\PyCharmProjects\server\venv\Scripts\python.exe
Python Version: 3.7.5
Python Path: 
['F:\\PyCharmProjects\\server\\TaichiGameServer',
 'I:\\Python37-64\\python37.zip',
 'I:\\Python37-64\\DLLs',
 'I:\\Python37-64\\lib',
 'I:\\Python37-64',
 'F:\\PyCharmProjects\\server\\venv',
 'F:\\PyCharmProjects\\server\\venv\\lib\\site-packages',
 'F:\\PyCharmProjects\\server\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.7.egg']
Server time: Tue, 24 Dec 2019 09:49:01 +0800
 
Traceback (most recent call last):
 File "F:\PyCharmProjects\server\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
  response = get_response(request)
 File "F:\PyCharmProjects\server\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
  response = self.process_exception_by_middleware(e, request)
 File "F:\PyCharmProjects\server\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
  response = wrapped_callback(request, *callback_args, **callback_kwargs)
 File "F:\PyCharmProjects\server\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
  return view_func(*args, **kwargs)
 File "F:\PyCharmProjects\server\venv\lib\site-packages\django\views\generic\base.py", line 71, in view
  return self.dispatch(request, *args, **kwargs)
 File "F:\PyCharmProjects\server\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
  response = self.handle_exception(exc)
 File "F:\PyCharmProjects\server\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
  self.raise_uncaught_exception(exc)
 File "F:\PyCharmProjects\server\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
  raise exc
 File "F:\PyCharmProjects\server\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
  response = handler(request, *args, **kwargs)
 File "F:\PyCharmProjects\server\venv\lib\site-packages\rest_framework\decorators.py", line 50, in handler
  return func(*args, **kwargs)
 File "F:\PyCharmProjects\server\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
  return view_func(*args, **kwargs)
 File "F:\PyCharmProjects\server\venv\lib\site-packages\ratelimit\decorators.py", line 23, in _wrapped
  request = args[1]
IndexError: tuple index out of range

总结

以上所述是小编给大家介绍的Django 限制访问频率的思路详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

Python 相关文章推荐
深入解析Python中的线程同步方法
Jun 14 Python
python之Socket网络编程详解
Sep 29 Python
Python实现感知机(PLA)算法
Dec 20 Python
Python检测网络延迟的代码
May 15 Python
Python测试网络连通性示例【基于ping】
Aug 03 Python
python找出完数的方法
Nov 12 Python
Python正则表达式如何匹配中文
May 27 Python
keras用auc做metrics以及早停实例
Jul 02 Python
flask项目集成swagger的方法
Dec 09 Python
python将YUV420P文件转PNG图片格式的两种方法
Jan 22 Python
Pytorch 统计模型参数量的操作 param.numel()
May 13 Python
告别网页搜索!教你用python实现一款属于自己的翻译词典软件
Jun 03 Python
python 统计文件中的字符串数目示例
Dec 24 #Python
如何基于python操作json文件获取内容
Dec 24 #Python
解决python 读取 log日志的编码问题
Dec 24 #Python
python实现按关键字筛选日志文件
Dec 24 #Python
python 实现提取log文件中的关键句子,并进行统计分析
Dec 24 #Python
Python3.7+tkinter实现查询界面功能
Dec 24 #Python
python 读取更新中的log 或其它文本方式
Dec 24 #Python
You might like
Terran魔法科技
2020/03/14 星际争霸
php面向对象全攻略 (十七) 自动加载类
2009/09/30 PHP
提示Trying to clone an uncloneable object of class Imagic的解决
2011/10/27 PHP
php递归获取目录内文件(包含子目录)封装类分享
2013/12/25 PHP
php一个文件搞定微信jssdk配置
2016/12/12 PHP
thinkphp框架类库扩展操作示例
2019/11/26 PHP
Javascript 函数对象的多重身份
2009/06/28 Javascript
8款非常棒的响应式jQuery 幻灯片插件推荐
2012/02/02 Javascript
弹出最简单的模式化遮罩层的js代码
2013/12/04 Javascript
jQuery实现有动画淡出效果的二级折叠菜单代码
2015/10/17 Javascript
BootStrap智能表单实战系列(七)验证的支持
2016/06/13 Javascript
IONIC自定义subheader的最佳解决方案
2016/09/22 Javascript
JavaScript页面实时显示当前时间实例代码
2016/10/23 Javascript
BootStrap表单时间选择器详解
2017/05/09 Javascript
详解Vue微信公众号开发踩坑全记录
2017/08/21 Javascript
微信小程序授权获取用户详细信息openid的实例详解
2017/09/20 Javascript
基于webpack-hot-middleware热加载相关错误的解决方法
2018/02/22 Javascript
详解webpack的proxyTable无效的解决方案
2018/06/15 Javascript
详解微信图片防盗链“此图片来自微信公众平台 未经允许不得引用”的解决方案
2019/04/04 Javascript
JS+HTML5本地存储Localstorage实现注册登录及验证功能示例
2020/02/10 Javascript
多种类型jQuery网页验证码插件代码实例
2021/01/09 jQuery
Python中的pass语句使用方法讲解
2015/05/14 Python
Python 装饰器实现DRY(不重复代码)原则
2018/03/05 Python
Python实现的微信好友数据分析功能示例
2018/06/21 Python
django model通过字典更新数据实例
2020/04/01 Python
Python实现网络聊天室的示例代码(支持多人聊天与私聊)
2021/01/27 Python
css3 box-shadow阴影(外阴影与外发光)图示讲解
2017/08/11 HTML / CSS
北欧最好的童装网上商店:Babyshop
2019/09/15 全球购物
How to spawning asynchronous work in J2EE
2016/08/29 面试题
高中英语演讲稿范文
2014/04/24 职场文书
社区党建工作方案
2014/06/10 职场文书
食堂管理制度范本
2015/08/04 职场文书
工作感想范文
2015/08/07 职场文书
初中班主任工作随笔
2015/08/15 职场文书
党风廉政建设心得体会(2016最新版)
2016/01/22 职场文书
基于Golang 高并发问题的解决方案
2021/05/08 Golang