django restframework权限和节流
权限
使用
权限是在认证之后,认证成功之后才控制权限。比如有些内容需要是vip可以查看,有些是超级vip可以查看。
from rest_framework.permissions import BasePermission
class MyPermission(BasePermission):
message = '无权限访问'
def has_permission(self, request, view):
user = User.objects.filter(name=request.user).first()
if user.get_level_display() == 'svip':
return True
return False
局部使用
class UserView(ModelViewSet):
permission_classes = [MyPermission]
queryset = User.objects.all()
serializer_class = UserSerializer
全局使用
REST_FRAMEWORK = {
'UNAUTHENTICATED_USER': None,
'UNAUTHENTICATED_TOKEN': None,
"DEFAULT_PERMISSION_CLASSES": [
"vue.utils.permission.MyPermission",
],
}
源码流程
频率控制
使用
自定义频率控制类
visit_dict = {}
import time
class MyThrottle(object):
"""一分钟3次"""
def __init__(self):
self.history = []
def allow_request(self, request, view):
remote_addr = request.META.get('REMOTE_ADDR')
ctime = int(time.time())
if remote_addr not in visit_dict:
visit_dict[remote_addr] = [ctime]
return True
else:
self.history = visit_dict[remote_addr]
while self.history and self.history[-1] < ctime - 60:
self.history.pop()
self.history.insert(0, ctime)
if len(self.history) <= 3:
return True
else:
return False
def wait(self):
"""
Optionally, return a recommended number of seconds to wait before
the next request.
"""
ctime = int(time.time())
return 60 - (ctime - self.history[-1])
在views.py中对应的视图中加上配置throttle_classes = [MyThrottle]
即可。
继承内在限流类
上述MyThrottle的代码逻辑django restframework已经帮我们完成了相应的逻辑部分,我们只需要更改做相应配置。
例如我们要做一个匿名用户5/m,登录用户10/m,管理员无访问限制的功能。vue.utils.throttle.py中的代码
from rest_framework.throttling import SimpleRateThrottle
class AnnoThrottle(SimpleRateThrottle):
scope = 'anno'
def get_cache_key(self, request, view):
if not request.user:
return self.get_ident(request)
else:
# 返回None就表示不走这个节流类
return None
class UserThrottle(SimpleRateThrottle):
scope = 'user'
def get_cache_key(self, request, view):
if request.user and request.user != 'admin':
return request.user
else:
return None
views.py中的代码:
class UserView(ModelViewSet):
throttle_classes = [AnnoThrottle, UserThrottle]
queryset = User.objects.all()
serializer_class = UserSerializer
def throttled(self, request, wait):
# raise exceptions.Throttled(wait)
# 定制中文显示信息
class MyThrottle(exceptions.Throttled):
default_detail = '请求被限制'
extra_detail_plural = '还需要再等{wait}秒'
raise MyThrottle(wait)
django settings的配置
REST_FRAMEWORK = {
"DEFAULT_THROTTLE_RATES":{
'anno':'5/m',
'user':'10/m',
}
}
源码流程
节流大体流程
内置节流类流程
class BaseThrottle(object):
"""
Rate throttling of requests.
"""
def allow_request(self, request, view):
"""
Return `True` if the request should be allowed, `False` otherwise.
"""
raise NotImplementedError('.allow_request() must be overridden')
def get_ident(self, request):
"""
获取标识,其实就是获取ip
"""
xff = request.META.get('HTTP_X_FORWARDED_FOR')
remote_addr = request.META.get('REMOTE_ADDR')
num_proxies = api_settings.NUM_PROXIES
if num_proxies is not None:
if num_proxies == 0 or xff is None:
return remote_addr
addrs = xff.split(',')
client_addr = addrs[-min(num_proxies, len(addrs))]
return client_addr.strip()
return ''.join(xff.split()) if xff else remote_addr
def wait(self):
"""
Optionally, return a recommended number of seconds to wait before
the next request.
"""
return None
我们自定义的节流类用一个全局变量的字典存数据,restframework考虑的使用缓存来存这些访问信息,而且使用的是django默认的缓存。看一下SimpleRateThrottle
的源码流程
class SimpleRateThrottle(BaseThrottle):
"""
A simple cache implementation, that only requires `.get_cache_key()`
to be overridden.
The rate (requests / seconds) is set by a `rate` attribute on the View
class. The attribute is a string of the form 'number_of_requests/period'.
Period should be one of: ('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day')
Previous request information used for throttling is stored in the cache.
"""
cache = default_cache
timer = time.time
cache_format = 'throttle_%(scope)s_%(ident)s'
scope = None
THROTTLE_RATES = api_settings.DEFAULT_THROTTLE_RATES
def __init__(self):
# 第1步:因为没有定义rate属性,走self.get_rate()
if not getattr(self, 'rate', None):
self.rate = self.get_rate()
# 第3步:得到限制次数和限制时间
self.num_requests, self.duration = self.parse_rate(self.rate)
def get_cache_key(self, request, view):
"""
Should return a unique cache-key which can be used for throttling.
Must be overridden.
May return `None` if the request should not be throttled.
"""
# 第5步:必须被重写
raise NotImplementedError('.get_cache_key() must be overridden')
def get_rate(self):
"""
Determine the string representation of the allowed request rate.
"""
# 第2步:判断有没有定义scope,没有就报错
if not getattr(self, 'scope', None):
msg = ("You must set either `.scope` or `.rate` for '%s' throttle" %
self.__class__.__name__)
raise ImproperlyConfigured(msg)
try:
# 去 THROTTLE_RATES(api_settings.DEFAULT_THROTTLE_RATES)这个字典里根据key为
# scope去取访问频率,如 "10/m" 这样的字符串,如果返回None表示不限制
return self.THROTTLE_RATES[self.scope]
except KeyError:
msg = "No default throttle rate set for '%s' scope" % self.scope
raise ImproperlyConfigured(msg)
def parse_rate(self, rate):
"""
Given the request rate string, return a two tuple of:
<allowed number of requests>, <period of time in seconds>
"""
# 第3步: 返回限制次数和限制时间
if rate is None:
return (None, None)
num, period = rate.split('/')
num_requests = int(num)
duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]]
return (num_requests, duration)
def allow_request(self, request, view):
"""
Implement the check to see if the request should be throttled.
On success calls `throttle_success`.
On failure calls `throttle_failure`.
"""
# 第4步:如果self.rate是None, 表示不限流
if self.rate is None:
return True
# 第5步:获取key,类似于我们自定义节流类获取的ip
self.key = self.get_cache_key(request, view)
# 第6步:如果想要不走这个节流类,就可以在自定义的get_cache_key返回None
# 这样就可以完全通过这个节流类了
if self.key is None:
return True
# 根据self.key去取访问信息,剩下的逻辑和自定义的节流类逻辑基本一致
self.history = self.cache.get(self.key, [])
self.now = self.timer()
# Drop any requests from the history which have now passed the
# throttle duration
while self.history and self.history[-1] <= self.now - self.duration:
self.history.pop()
if len(self.history) >= self.num_requests:
return self.throttle_failure()
return self.throttle_success()
def throttle_success(self):
"""
Inserts the current request's timestamp along with the key
into the cache.
"""
self.history.insert(0, self.now)
self.cache.set(self.key, self.history, self.duration)
return True
def throttle_failure(self):
"""
Called when a request to the API has failed due to throttling.
"""
return False
def wait(self):
"""
Returns the recommended next request time in seconds.
"""
if self.history:
remaining_duration = self.duration - (self.now - self.history[-1])
else:
remaining_duration = self.duration
available_requests = self.num_requests - len(self.history) + 1
if available_requests <= 0:
return None
return remaining_duration / float(available_requests)
补充
self.initial(request, *args, **kwargs)
中完成了四件事,版本,认证,权限和节流,在self.initial(request, *args, **kwargs)
外层有try语句块来捕捉异常,所以从前到后,从版本到认证,从认证到权限,从权限到节流,四个环节的任何一个环节出现错误都会主动抛出异常(从源码就可以看出),接下来的环节都不会执行,只有前面一个环节按照规定的走完才会走下一个环节。其实,这也是符合我们正常的开发逻辑的。只有先认证成功才会谈权限,只有有了不同权限才会有不同访问评率的说法