最近做了一个系统由于部分接口需要进行耗时操作,因而不希望用户进行频繁访问,需要进行访问频率限制。如果要自己实现一个访问限制功能相对来说也不会太复杂,并且网上有各种代码可以参考。如果自己不想实现这个代码可以使用 Django Ratelimit 。
Django Ratelimit is a ratelimiting decorator for Django views. https://travis-ci.org/jsocol/django-ratelimit.png"htmlcode">@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 限制访问频率的思路详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。
更新日志
- 明达年度发烧碟MasterSuperiorAudiophile2021[DSF]
- 英文DJ 《致命的温柔》24K德国HD金碟DTS 2CD[WAV+分轨][1.7G]
- 张学友1997《不老的传说》宝丽金首版 [WAV+CUE][971M]
- 张韶涵2024 《不负韶华》开盘母带[低速原抓WAV+CUE][1.1G]
- lol全球总决赛lcs三号种子是谁 S14全球总决赛lcs三号种子队伍介绍
- lol全球总决赛lck三号种子是谁 S14全球总决赛lck三号种子队伍
- 群星.2005-三里屯音乐之男孩女孩的情人节【太合麦田】【WAV+CUE】
- 崔健.2005-给你一点颜色【东西音乐】【WAV+CUE】
- 南台湾小姑娘.1998-心爱,等一下【大旗】【WAV+CUE】
- 【新世纪】群星-美丽人生(CestLaVie)(6CD)[WAV+CUE]
- ProteanQuartet-Tempusomniavincit(2024)[24-WAV]
- SirEdwardElgarconductsElgar[FLAC+CUE]
- 田震《20世纪中华歌坛名人百集珍藏版》[WAV+CUE][1G]
- BEYOND《大地》24K金蝶限量编号[低速原抓WAV+CUE][986M]
- 陈奕迅《准备中 SACD》[日本限量版] [WAV+CUE][1.2G]