根据金字塔中的请求matchdict设置视图权限

时间:2014-02-04 19:42:04

标签: python pyramid

如果我添加路线然后添加视图,我如何根据金字塔中的请求matchdict设置视图权限?我的意思是:

config.add_route('full_reg', '{base}/reg/{id}/full', factory=RegContextFactory)
config.add_view(view=RegCustomView, attr='full_reg', route_name='full_reg', request_method='GET', 
    permission=request.matchdict["base"])

当然,我没有“请求”对象,但我怎么能这样做?

修改:添加代码。 以下是课程:

class RegContextFactory():  

    @property
    def __acl__(self):
        return [
            (Allow, 'g:users', 'x'),
            (Allow, 'g:users2', 'y'),
        ]   

    def __init__(self, request):
        self.request = request

class RegCustomView():    

    def __init__(self, context, request):
        self.context = context
        self.request = request

    def full_reg(self):
         # if the user is not from users group, or the base param is not 'x',
         #then this view should be forbidden
         base = self.request.matchdict.get('base')
         return Response('ok')

1 个答案:

答案 0 :(得分:0)

使用用户回调函数的解决方案:

# This should be in RegContextFacory
__acl__ = [
    (Allow, 'group:viewers', 'view'),
    (Allow, 'group:creators', 'create'),
    (Allow, 'group:editors', 'edit'),
    (Allow, 'group:deleters', 'delete'),
    (Allow, Authenticated, ALL_PERMISSIONS),
    (Deny, Everyone, ALL_PERMISSIONS),
]


def user_callback(user_name, request):

    if user_name == 'admin':
        return 'Authenticated'

    base = request.matchdict.get('base')
    resource = request.matchdict.get('id')
    auth_provider = AuthProvider(user_name, base, resource)
    return auth_provider.get_permission() #Should return somtehing like ['group:viewers']