Django API请求次数限制

为了防止登陆接口被爆破,我们需要进行访问次数限制。在此记录使用中间件的实现方案。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import uuid

from django.core.cache import cache
from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
from django.utils.translation import gettext as _

from desert import settings


class RequestRestrictionMiddleware(MiddlewareMixin):
def process_request(self, request):
identify = request.session.get('identify')
requested_times = cache.get(identify)
if requested_times is not None:
if int(requested_times) >= settings.REQUEST_LIMIT:
return JsonResponse({'status': 'error', 'message': _('To many request')}, status=400)
else:
cache.set(identify, requested_times + 1)
else:
identify = request.session['identify'] = uuid.uuid4()
cache.set(identify, 1, settings.REQUEST_LIMIT_TIME)

此外要记得在 setting.py 中配置中间件和相关字段。

Django API请求次数限制

https://www.phakel.cn/2022-04-07/abae205/

作者

EvanLuo42

发布于

2022-04-07

更新于

2022-04-07

许可协议

评论

+ +