我需要创建一个嵌套路由。看起来像api/<campaign-name>/content/<content-id>
。我知道有一些包(this和this)可以创建嵌套路由。我试过它们并且相当有限。所以我决定硬连接网址。网址和观点如下:
在urls.py
# contents
## detail, update, remove
url(
r'^api/campaign/(?P<campaign>[a-z0-9-]+)/content/(?P<content>\d+)/$',
ContentAPI.as_view({'get' : 'retrieve', 'put' : 'update', 'delete' : 'destroy'}),
name = "content-detail"
),
## toggle content verification
url(
r'^api/campaign/(?P<campaign>[a-z0-9-]+)/content/(?P<content>\d+)/toggle_status/$',
ContentAPI.as_view(
{'post' : 'toggle_status'},
permission_classes = [Or(IsContentManager, IsContentModerator)]
),
name = "content-toggle-status"
),
在views.py
class ContentAPI(viewsets.ModelViewSet):
permission_classes = [Or(IsContentManager)]
... # actions and methods here
一切正常,但权限似乎不起作用。无需登录系统即可访问API。如何在我的方案中强制执行权限。
答案 0 :(得分:0)
错误在我身边。当我使用router.register('api/(?P<domain>[a-z0-9]+)/sub-domain/(?P<sub_domain>[a-z0-9]+), SubdomainAPI)
生成嵌套路由时,我必须在SubdomainAPI处过滤domain
。
所以我在initial()
:
def initial(self, request, *args, **kwargs):
self.domain = self._get_domain()
super(SubdomainAPI, self).initial(request, *args, **kwargs)
self._get_domain()
检查域是否存在并引发404错误。由于在权限检查之前提出了404错误,因此我的测试失败了。
应该是:
def initial(self, request, *args, **kwargs):
super(SubdomainAPI, self).initial(request, *args, **kwargs)
self.domain = self._get_domain()
希望如果其他人遇到类似的问题,这将会有所帮助。