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

作者:h4ck 时间:2021-08-17 16:52:57 

最近做了一个系统由于部分接口需要进行耗时操作,因而不希望用户进行频繁访问,需要进行访问频率限制。如果要自己实现一个访问限制功能相对来说也不会太复杂,并且网上有各种代码可以参考。如果自己不想实现这个代码可以使用 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 限制访问频率的思路详解网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

来源:http://www.h4ck.org.cn/2019/12/django-限制访问频率/

标签:Django,访问,频率
0
投稿

猜你喜欢

  • python @classmethod 的使用场合详解

    2023-08-02 20:50:35
  • 解决VUE自定义拖拽指令时 onmouseup 与 click事件冲突问题

    2024-05-10 14:15:54
  • jQuery结合CSS制作漂亮的select下拉菜单

    2024-04-19 09:58:32
  • python使用Plotly绘图工具绘制散点图、线形图

    2022-06-24 08:11:50
  • Python操作dict时避免出现KeyError的几种解决方法

    2022-12-30 14:48:26
  • vuex mutations的两种调用方法小结

    2024-04-27 16:11:42
  • asp文章上一篇,下一篇实现代码

    2008-03-24 20:15:00
  • Window下Mysql忘记root密码怎么重置

    2024-01-15 22:33:23
  • 有关Server.Mappath详细接触

    2010-07-07 11:35:00
  • Web设计师的出路问题

    2009-06-08 13:07:00
  • Python中规范定义命名空间的一些建议

    2022-05-16 17:05:24
  • python和mysql交互操作实例详解【基于pymysql库】

    2024-01-16 01:03:47
  • pandas通过索引进行排序的示例

    2021-04-21 04:19:55
  • Oracle数据库系统使用经验六则

    2010-07-26 13:22:00
  • Python实现C#代码生成器应用服务于Unity示例解析

    2023-01-18 00:33:44
  • django 解决model中类写不到数据库中,数据库无此字段的问题

    2024-01-24 17:52:07
  • 无级分类的多级联动

    2020-07-02 12:53:12
  • Python编程中使用Pillow来处理图像的基础教程

    2021-07-20 10:53:19
  • Python 如何实现访问者模式

    2021-08-10 20:49:53
  • 十行Python代码制作一个视频倒放神器

    2022-02-03 13:40:15
  • asp之家 网络编程 m.aspxhome.com