gpt4 book ai didi

python - 可重复使用的应用程序和访问控制

转载 作者:行者123 更新时间:2023-11-28 19:15:24 32 4
gpt4 key购买 nike

假设我创建了一个(希望如此)可重复使用的应用程序 fooapp:

网址.py

urls('^(?P<userid>\d+)/$', views.show_foo),

和 fooapp 的 views.py:

def show_foo(request, userid):
usr = shortcuts.get_object_or_404(User, pk=userid)
... display a users' foo ...
return render_to_response(...)

因为它是一个可重复使用的应用程序,所以它没有指定任何访问控制(例如 @login_required)。

在站点/项目 urls.py 中,包含应用程序:

urls('^foo/', include('fooapp.urls')),

我如何/在哪里可以指定在这个站点中只有工作人员应该被授予访问权限以查看用户的 foo?

如果除了工作人员之外,用户还应该能够查看自己的 foo (login_required + request.user.id == userid) 怎么样?

我没有找到任何明显的参数来包含..

注意:这与访问控制有关,与权限无关,即 require_staff 检查 User.is_stafflogin_required 检查 request.user 是否登录,用户查看自己的页面如上所述。这个问题是关于网站如何为可重用应用程序指定访问控制。

最佳答案

好吧,我找到了一种通过迭代 Django 的 include 返回的模式来工作的方法:

from django.core.urlresolvers import RegexURLPattern, RegexURLResolver

def urlpatterns_iterator(patterns):
"""Recursively iterate through `pattern`s.
"""
_patterns = patterns[:] # create a copy

while _patterns:
cur = _patterns.pop()
if isinstance(cur, RegexURLPattern):
yield cur
elif isinstance(cur, RegexURLResolver):
_patterns += cur.url_patterns
else:
raise ValueError("I don't know how to handle %r." % cur)

def decorate(fn, (urlconf_module, app_name, namespace)):
"""Iterate through all the urls reachable from the call to include and
wrap the views in `fn` (which should most likely be a decorator).

(the second argument is the return value of Django's `include`).
"""
# if the include has a list of patterns, ie.: url(<regex>, include([ url(..), url(..) ]))
# then urlconf_module doesn't have 'urlpatterns' (since it's already a list).
patterns = getattr(urlconf_module, 'urlpatterns', urlconf_module)
for pattern in urlpatterns_iterator(patterns):
# the .callback property will set ._callback potentially from a string representing the path to the view.
if pattern.callback:
# the .callback property doesn't have a setter, so access ._callback directly
pattern._callback = fn(pattern._callback)
return urlconf_module, app_name, namespace

然后在站点/项目的 urls.py 中使用它,因此代替:

urls('^foo/', include('fooapp.urls')),

一个会做:

from django.contrib.admin.views.decorators import staff_member_required as _staff_reqd

def staff_member_required(patterns): # make an include decorator with a familiar name
return decorate(_staff_reqd, patterns)

...
urls('^foo/', staff_member_required(include('fooapp.urls'))),

关于python - 可重复使用的应用程序和访问控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34159495/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com