作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试编写自定义 rest_framework 权限,以防止用户查询与他们不同公司的信息。不幸的是,我似乎无法从 has_permission()
中访问任何 URL 参数。或 has_object_permissions()
.
这是我的路由器的开头:
# Create a basic router
router = routers.SimpleRouter()
# Establish some variables to assist with nested routes
root_elem = 'companies'
root_elem_id = '/(?P<company_id>[0-9]+)'
loca_elem = '/locations'
loca_elem_id = '/(?P<location_id>[0-9]+)'
# Companies will be the root from which all other relations branch
router.register(r'' + root_elem, views.CompanyViewSet)
router.register(r'' + root_elem + root_elem_id + loca_elem,
views.LocationViewSet)
# Only permit actions originating from location managers or company admins
class IsLocationManagerOrHigher(BasePermission):
# Checked when displaying lists of records
def has_permission(self, request, *args, **kwargs):
is_correct_level = False
# Admins can see every location if their location_id
# matches a location that's a child of the company
# specified in the URL
if request.employee.is_admin:
is_correct_level = True
return request.user and is_correct_level
# Checked when viewing specific records
def has_object_permission(self, request, view, obj):
is_correct_level = False
# Admins can see location details if their location's company_id
# matches a Location's company_id
if request.employee.is_admin:
is_correct_level = True
# Managers can see location details if it's their location
elif obj.id == request.employee.location_id and request.employee.is_manager:
is_correct_level = True
return request.user and is_correct_level
request.employee.is_admin
只是我需要的一半 - 我还需要访问
company_id
来自 URL 并确保它匹配管理员的位置
company_id
:
# Pseudocode
try:
user_location = Location.objects.get(id=request.employee.location_id)
return user_location.company_id == kwargs['company_id']
except ObjectDoesNotExist:
pass
最佳答案
如果你不能直接传递它们(这会更好),它们在请求对象上可用:
company_id = request.resolver_match.kwargs.get('company_id')
request.resolver_match.args
和
request.resolver_match.kwargs
包含在您的 url 中捕获的位置/关键字参数。
关于django - 如何从 BasePermission 中访问 URL 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29660423/
我是一名优秀的程序员,十分优秀!