是not hard to check获得 Pyramid 中特定资源的许可。我想知道如何确定某个路由对应的权限类型和资源。
详情假设我添加了一条路线
config.add_route('resource.edit', '/t/{resource_id:\d+}/edit',
factory = FactoryFactory('resource') ))
其中 FactoryFactory
是一个返回工厂的函数。在这种情况下,它会为“资源” 返回一个工厂,无论它是什么。稍后,我会这样:
@view_config(
route_name='resource.edit',
renderer='resource-edit.pt',
permission='edit'
)
def edit(resource_object, request):
...
有时,我会在网站上生成一个输入元素,链接到
request.route_url('resource.edit', resource_id=some_input)
编辑: 根据要求,我会给您准确的模板代码,希望这能让您更好地了解情况。我们使用的模板引擎是 Chameleon。
<a href="${request.route_url('resource.edit', resource_id=res.id)}"
class="btn btn-info morespacing"><i class="icon-edit"></i>edit</a>
现在我想要的是这样的:
<a tal:condition="h.route_accessible(request, 'resource.edit', res.id)"
href="${request.route_url('resource.edit', resource_id=res.id)}"
class="btn btn-info morespacing"><i class="icon-edit"></i>edit</a>
换句话说:如果用户一开始就有权执行编辑操作,我想仅显示此输入元素。
现在,我可以给你一个例子,说明什么可行但对我没有吸引力,因为它不灵活。我编写了一个辅助函数
def can_edit(request, factory_type, res_id):
resource = FactoryFactory(factory_type)(res_id)
return has_permission('edit', resource, request)
然后我写
<a tal:condition="h.can_edit(request, 'resource', res.id)"
href="${request.route_url('resource.edit', resource_id=res.id)}"
class="btn btn-info morespacing"><i class="icon-edit"></i>edit</a>
这对我来说没有吸引力,因为有关工厂的信息和有关权限的信息已编码到路由中,所以我觉得我应该能够通过简单地提供来访问它路线的名称。
因此,我正在寻找一种从仅路由信息获取资源和权限的方法,即从字符串'resource.edit'
和资源id some_input
。这可能吗?如果是,如何?
非常感谢您。
最佳答案
针对您的问题:
Therefore, I am looking for a way to obtain the resource and the permission from only the route information, i.e. from the string 'resource.edit' and the resource id some_input. Is this possible? If yes, how?
在您向 Pyramid 提供资源之前,Pyramid 无法知道用户(当前请求)是否能够访问您的资源。可以引用
Assigning ACLs to your Resource Objects
如您所见,Pyramid 将查看资源对象的 __ACL__ 属性(以及资源祖先的 __ACL__ ),然后确定谁对此资源具有何种权限,因此,Pyramid 默认授权是不可能的政策。
要解决您的问题,您可以自定义 AuthorizationPolicy ,制定您自己的授权规则,或者您可以轻松地从 ID 创建资源。
想一想,如果你有一个资源对应表的owner
字段,你需要检查当前用户是否是特定资源的所有者,你将需要获取该资源无论如何从数据库。因此,无论如何您都需要创建一个提供 __ACL__ 属性的资源。所以,我的建议是,让创建资源更容易,让它像这样 Resource(res.id)
,这样你就可以像这样编写你的模板
<a tal:condition="has_permission('edit', Resource(res.id), request)"
href="${request.route_url('resource.edit', resource_id=res.id)}"
class="btn btn-info morespacing"><i class="icon-edit"></i>edit</a>
更新
然后我认为你需要的是使用内省(introspection)器来获取工厂并像这样创建资源
def has_permission_for_route(request, route_name, permission, res_id):
introspector = request.registry.introspector
route_name = request.matched_route.name
route_intr = introspector.get('routes', route_name)
factory = route_intr['factory']
resource = factory(request, res_id=res_id)
return has_permission(permission, resource, request)
关于python - Pyramid :检查给定路由名称的权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20926733/