我使用DJANGO REST框架来保护我的API。Django节流,限制匿名API上的请求数量并对用户进行身份验证。
节流在生产模式下不起作用。顺便说一下,我使用Ubuntu和Nginx服务器来部署我的站点。
我使用了两种方法,但这两种方法对我都不起作用。以下是代码。请帮帮我。我是姜戈的菜鸟。
我使用的第一种方法如下所述。Views.py
class SustainedAnon(AnonRateThrottle):
rate = '100/day'
class BurstAnon(AnonRateThrottle):
rate = '10/minute'
class SustainedUser(UserRateThrottle):
rate = '100/day'
class BurstUser(UserRateThrottle):
rate = '10/min'
class ProductApi(generics.RetrieveAPIView, mixins.CreateModelMixin):
lookup_field= 'puid'
serializer_class = ProductApisSerializers
"""
Provides a get method handler.
"""
# permission_classes = (IsAuthenticated,)
throttle_classes = (SustainedAnon,SustainedUser,BurstAnon,BurstUser)
def get_queryset(self):
return ProductApis.objects.all()
def post(self, request,*args,**kwargs):
return self.create(request, *args, **kwargs)
URLS.PY
from django.contrib import admin
from django.urls import path, include
from . import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
path('',views.index, name='index'),
path('api/<slug:puid>/',views.ProductApi.as_view()),
]
第二种方法- DRF
Views.py
class ProductApi(generics.RetrieveAPIView, mixins.CreateModelMixin):
lookup_field= 'puid'
serializer_class = ProductApisSerializers
"""
Provides a get method handler.
"""
# permission_classes = (IsAuthenticated,)
throttle_classes = [UserRateThrottle,AnonRateThrottle]
def get_queryset(self):
return ProductApis.objects.all()
def post(self, request,*args,**kwargs):
return self.create(request, *args, **kwargs)
settings.py
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
],
'DEFAULT_THROTTLE_RATES': {
'anon': '20/minute',
'user': '10/minute',
}
}
此外,在第一种方法中,我没有在settings.py文件中做任何更改,而在第二种方法中,我添加了额外的DRF代码来控制节流。
这两种方法对我都不起作用。
发布于 2019-10-15 20:52:18
在生产中使用LocMemCache
会导致随机结果。您可能正在使用多个进程,这意味着每个进程都有各自独立的缓存。任何缓存在一个进程中的东西都不能被其他进程使用。
使用单个进程,就像对runserver
所做的那样,使缓存保持一致。
TL;DR,不要在生产中使用LocMemCache
。请使用Redis、Memcache或其他共享缓存。
https://stackoverflow.com/questions/58398685
复制相似问题