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中精确输出JSON浮点数的方法
Apr 18 Python
python编写网页爬虫脚本并实现APScheduler调度
Jul 28 Python
pandas.DataFrame 根据条件新建列并赋值的方法
Apr 08 Python
python3.4.3下逐行读入txt文本并去重的方法
Apr 29 Python
数据清洗--DataFrame中的空值处理方法
Jul 03 Python
使用pyecharts生成Echarts网页的实例
Aug 12 Python
python+opencv实现车牌定位功能(实例代码)
Dec 24 Python
Python Tensor FLow简单使用方法实例详解
Jan 14 Python
Pytorch maxpool的ceil_mode用法
Feb 18 Python
Flask模板引擎Jinja2使用实例
Apr 23 Python
细说NumPy数组的四种乘法的使用
Dec 18 Python
OpenCV-Python实现油画效果的实例
Jun 08 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
php操作xml入门之cdata区段
2015/01/23 PHP
判断、添加和删除WordPress置顶文章的相关PHP函数小结
2015/12/10 PHP
非集成环境的php运行环境(Apache配置、Mysql)搭建安装图文教程
2016/04/12 PHP
php 魔术常量详解及实例代码
2016/12/04 PHP
PHP实现表单提交时去除斜杠的方法
2016/12/26 PHP
php创建类并调用的实例方法
2019/09/25 PHP
JS 如何获取radio选中后的值及不选择取radio的值
2013/10/28 Javascript
jquery html动态生成select标签出问题的解决方法
2013/11/20 Javascript
跟我学习javascript的var预解析与函数声明提升
2015/11/16 Javascript
BootStrap扔进Django里的方法详解
2016/05/13 Javascript
微信小程序 Video API实例详解
2016/10/02 Javascript
React服务端渲染(总结)
2017/07/01 Javascript
极简主义法编写JavaScript类
2017/11/02 Javascript
JS排序算法之希尔排序与快速排序实现方法
2017/12/12 Javascript
15 分钟掌握vue-next响应式原理
2019/10/13 Javascript
微信小程序淘宝首页双排图片布局排版代码(推荐)
2020/10/29 Javascript
element-ui点击查看大图的方法示例
2020/12/14 Javascript
[02:31]《DAC最前线》之选手酒店现场花絮
2015/01/30 DOTA
在Python中操作文件之truncate()方法的使用教程
2015/05/25 Python
python数据处理实战(必看篇)
2017/06/11 Python
Python从数据库读取大量数据批量写入文件的方法
2018/12/10 Python
python实现贪吃蛇游戏
2020/03/21 Python
Python爬虫 urllib2的使用方法详解
2019/09/23 Python
Python logging模块写入中文出现乱码
2020/05/21 Python
如何使用Cython对python代码进行加密
2020/07/08 Python
外贸采购员求职的自我评价
2013/11/26 职场文书
致800米运动员广播稿
2014/02/16 职场文书
委托书的写法
2014/09/16 职场文书
预备党员个人总结
2015/02/14 职场文书
银行先进个人总结
2015/02/15 职场文书
2015年扫黄打非工作总结
2015/05/13 职场文书
cf战队宣传语
2015/07/13 职场文书
小学生暑假生活总结
2015/07/13 职场文书
Pytest allure 命令行参数的使用
2021/04/18 Python
pytorch中的numel函数用法说明
2021/05/13 Python
python 解决微分方程的操作(数值解法)
2021/05/26 Python