我正在尝试构建自己的IP地址黑名单拦截器。
我找到了Django DRF以及相关的SO问题和答案,但很难实现这一点。
我的IpTable模型有ip_address字段。
我修改了文档示例,如下所示:
from rest_framework import permissions
class BlacklistPermission(permissions.BasePermission):
"""
Global permission check for blacklisted IPs.
"""
def has_permission(self, request, view):
ip_address = request.META['REMOTE_ADDR']
blacklisted = IpTable.objects.filter(ip_address=ip_address).exists()
return blacklisted ## (if ip address in table returns True)
问题是:我想阻止用户的视图如何使用它?
想法是在视图之前创建装饰吗?
或者在其余代码之前调用全局权限检查进入视图?
在其中任何一个选项中,全局权限检查的语法是什么?
还必须有逻辑来做某事,例如重定向到403页面或自定义页面。它是视图中的if语句还是全局权限检查函数?
编辑添加:
DRF文件说
"Object level permissions are run by REST framework's generic views
when **.get_object()** is called. As with view level permissions, an
exceptions.PermissionDenied exception will be raised if the user
is not allowed to act on the given object."
OR
"If you're writing your own views and want to enforce object level
permissions, or if you override the get_object method on a generic
view, then you'll need to explicitly call the
**.check_object_permissions(request, obj)** method on the view at the
point at which you've retrieved the object."
"These will either raise a PermissionDenied or NotAuthenticated exception
, or simply return if the view has the appropriate permissions."
然后给出了这个通用的例子:
def get_object(self):
obj = get_object_or_404(self.get_queryset())
self.check_object_permissions(self.request, obj)
return obj
假设我的观点如下:
def country(request, country_id):
country = Countries.objects.get(id=country_id)
通用示例中提到的对象是什么?我想检查的是请求用户的IP地址。这是由has_permission
类中的BlacklistPermission
函数检查的。
将请求用户发送到has_permission
类中的BlacklistPermission
函数的表达式语法是什么?
是否类似于以下
def country(request, country_id):
permission = request.user.check_object_permissions(request, request.user)
if permission:
country = Countries.objects.get(id=country_id)
else:
pass