您可以通过在Report 模型中定义__acl__() 来使用Pyramid authorization policy。例如:
from sqlalchemy.orm import relationship, backref
from pyramid.security import Everyone, Allow
class Report(Base):
# ...
user_id = Column(Integer, ForeignKey('user.id'))
# ...
@property
def __acl__(self):
return [
(Allow, Everyone, 'view'),
(Allow, self.user_id, 'edit'),
]
# this also works:
#__acl__ = [
# (Allow, Everyone, 'view'),
# (Allow, self.user_id, 'edit'),
#]
class User(Base):
# ...
reports = relationship('Report', backref='user')
上面的__acl__()将允许所有人调用你的视图view,但只有与Report相关的用户才能调用edit它。
引用documentation,您可能没有启用身份验证策略或授权策略:
使用配置器的 set_authorization_policy() 方法启用授权策略。
您还必须启用身份验证策略才能启用授权策略。这是因为授权通常取决于身份验证。在应用程序设置期间使用 set_authentication_policy() 和方法来指定身份验证策略。
from pyramid.config import Configurator
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
authentication_policy = AuthTktAuthenticationPolicy('seekrit')
authorization_policy = ACLAuthorizationPolicy()
config = Configurator()
config.set_authentication_policy(authentication_policy)
config.set_authorization_policy(authorization_policy)
上述配置启用了一个策略,该策略将在请求环境中传递的“auth ticket”cookie 的值进行比较,该 cookie 包含对单个主体的引用,与在尝试调用某些资源时在资源树中找到的任何 ACL 中存在的主体查看。
虽然可以混合和匹配不同的身份验证和授权策略,但使用身份验证策略但没有授权策略配置 Pyramid 应用程序是错误的,反之亦然。如果这样做,您将在应用程序启动时收到错误消息。