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 相关文章推荐
35个Python编程小技巧
Apr 01 Python
Python在Windows和在Linux下调用动态链接库的教程
Aug 18 Python
Python操作RabbitMQ服务器实现消息队列的路由功能
Jun 29 Python
Centos7 Python3下安装scrapy的详细步骤
Mar 15 Python
详解PyTorch批训练及优化器比较
Apr 28 Python
flask框架视图函数用法示例
Jul 19 Python
Python3安装Pillow与PIL的方法
Apr 03 Python
详解Python列表赋值复制深拷贝及5种浅拷贝
May 15 Python
PyTorch搭建多项式回归模型(三)
May 22 Python
Python 获取ftp服务器文件时间的方法
Jul 02 Python
Python中生成ndarray实例讲解
Feb 22 Python
python实现对doc、txt、xls等文档的读写操作
Apr 02 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中instanceof关键字及instanceof关键字有什么作用
2015/11/05 PHP
Laravel框架生命周期与原理分析
2018/06/12 PHP
php ajax数据传输和响应方法
2018/08/21 PHP
如何在centos8自定义目录安装php7.3
2019/11/28 PHP
自动生成文章摘要的代码[JavaScript 版本]
2007/03/20 Javascript
实现连缀调用的map方法(prototype)
2009/08/05 Javascript
引用 js在IE与FF之间的区别详细解析
2013/11/20 Javascript
js解决弹窗问题实现班级跳转DIV示例
2014/01/06 Javascript
jquery序列化form表单使用ajax提交后处理返回的json数据
2014/03/03 Javascript
jQuery中的height innerHeight outerHeight区别示例介绍
2014/06/15 Javascript
JavaScript DOM操作表格及样式
2015/04/13 Javascript
vue组件 $children,$refs,$parent的使用详解
2017/07/31 Javascript
微信小程序 本地图片按照屏幕尺寸处理
2017/08/04 Javascript
vue项目关闭eslint校验
2018/03/21 Javascript
如何用RxJS实现Redux Form
2018/12/29 Javascript
Python3搜索及替换文件中文本的方法
2015/05/22 Python
Python处理CSV与List的转换方法
2018/04/19 Python
Django中STATIC_ROOT和STATIC_URL及STATICFILES_DIRS浅析
2018/05/08 Python
使用python的pexpect模块,实现远程免密登录的示例
2019/02/14 Python
Python对ElasticSearch获取数据及操作
2019/04/24 Python
Python使用mongodb保存爬取豆瓣电影的数据过程解析
2019/08/14 Python
python3.6使用SMTP协议发送邮件
2020/05/20 Python
python 生成器需注意的小问题
2020/09/29 Python
世界汽车零件:World Car Parts
2019/09/04 全球购物
您在慕尼黑的跑步商店:Lauf-bar
2019/10/11 全球购物
入党自我鉴定范文
2013/10/04 职场文书
企业车辆管理制度
2014/01/24 职场文书
兰兰过桥教学反思
2014/02/08 职场文书
改进作风怎么办发言材料
2014/08/17 职场文书
2016党员学习心得体会范文
2016/01/23 职场文书
2019大学毕业晚会主持词
2019/06/21 职场文书
心得体会该怎么写呢?
2019/06/27 职场文书
python迷宫问题深度优先遍历实例
2021/06/20 Python
CSS 伪元素::marker详解
2021/06/26 HTML / CSS
中国古风插画师排行榜:夏达第一,第三是阴阳师姑获鸟皮肤创作者
2022/03/18 国漫
MySql如何将查询的出来的字段进行转换
2022/06/14 MySQL