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文件操作之目录遍历实例分析
May 20 Python
Python编程中字符串和列表的基本知识讲解
Oct 14 Python
python实现感知器算法详解
Dec 19 Python
python pandas.DataFrame选取、修改数据最好用.loc,.iloc,.ix实现
Jun 11 Python
Python 从相对路径下import的方法
Dec 04 Python
浅谈python str.format与制表符\t关于中文对齐的细节问题
Jan 14 Python
Python数据可视化库seaborn的使用总结
Jan 15 Python
python读取.mat文件的数据及实例代码
Jul 12 Python
Django Aggregation聚合使用方法解析
Aug 01 Python
应用OpenCV和Python进行SIFT算法的实现详解
Aug 21 Python
Python 如何操作 SQLite 数据库
Aug 17 Python
python读取mat文件生成h5文件的实现
Jul 15 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
SESSION信息保存在哪个文件目录下以及能够用来保存什么类型的数据
2012/06/17 PHP
php中serialize序列化与json性能测试的示例分析
2013/04/27 PHP
php fsockopen伪造post与get方法的详解
2013/06/14 PHP
PHP实现的多彩标签效果代码分享
2014/08/21 PHP
php中JSON的使用方法
2015/04/30 PHP
php如何控制用户对图片的访问 PHP禁止图片盗链
2016/03/25 PHP
PHP+Ajax简单get验证操作示例
2019/03/02 PHP
模仿JQuery.extend函数扩展自己对象的js代码
2009/12/09 Javascript
基于jquery的复制网页内容到WORD的实现代码
2011/02/16 Javascript
jquery实现excel导出的方法
2013/04/04 Javascript
使用JavaScript获取地址栏参数的方法
2014/12/19 Javascript
高效的jquery数字滚动特效
2015/12/17 Javascript
JS操作COOKIE实现备忘记录的方法
2016/04/01 Javascript
jQuery插件HighCharts实现的2D回归直线散点效果示例【附demo源码下载】
2017/03/09 Javascript
使用AngularJS2中的指令实现按钮的切换效果
2017/03/27 Javascript
node链接mongodb数据库的方法详解【阿里云服务器环境ubuntu】
2019/03/07 Javascript
layui动态表头的实现代码
2019/08/22 Javascript
node省市区三级数据性能测评实例分析
2019/11/06 Javascript
JS实现canvas简单小画板功能
2020/06/23 Javascript
[50:54]完美世界DOTA2联赛 GXR vs IO 第三场 11.07
2020/11/10 DOTA
浅析Python多线程下的变量问题
2015/04/28 Python
按日期打印Python的Tornado框架中的日志的方法
2015/05/02 Python
在Python的Flask中使用WTForms表单框架的基础教程
2016/06/07 Python
详解python如何调用C/C++底层库与互相传值
2016/08/10 Python
python Flask实现restful api service
2017/12/04 Python
Python3多线程操作简单示例
2018/05/22 Python
对dataframe进行列相加,行相加的实例
2018/06/08 Python
python获取当前文件路径以及父文件路径的方法
2019/07/10 Python
python实现按关键字筛选日志文件
2019/12/24 Python
python获取栅格点和面值的实现
2020/03/10 Python
Python多线程通信queue队列用法实例分析
2020/03/24 Python
Django-migrate报错问题解决方案
2020/04/21 Python
党的群众路线教育实践活动领导班子对照检查材料
2014/09/25 职场文书
会计实训报告范文
2014/11/04 职场文书
快消品行业营销模式与盈利模式分享
2019/09/27 职场文书
Python线程池与GIL全局锁实现抽奖小案例
2022/04/13 Python