【问题标题】:'Role' object has no attribute '__name__'“角色”对象没有属性“__name__”
【发布时间】:2012-06-24 09:59:23
【问题描述】:

我正在尝试在我的应用程序中实现基于角色的权限。我有一个装饰器 role_required,我可以将一组用户角色传递给其中,并且只有具有该角色的用户才能访问该视图。我已经为用户正确分配了角色,但是现在我收到 AttributeError 声明 'Role' object has no attribute '__name__'

views.py文件:

m_role_required = method_decorator(role_required)
class AddProposal(FormView):

    @m_role_required(roles.space_admin)
    def dispatch(self, *args, **kwargs):
        return super(AddProposal, self).dispatch(*args, **kwargs)

装饰师role_required:

from django.contrib.auth.decorators import user_passes_test
def role_required(*roles):

    def check_role(user):
        return getattr(user, 'role', None) in roles
    return user_passes_test(check_role)

Role 类:

class Roles(object):
    _roles_dict = None

    @property
    def roles_dict(self):

        if self._roles_dict is None:
            self._roles_dict = {}
            for item in self._config:
                if isinstance(item, basestring):
                    # An item like 'manager'
                    self._roles_dict[item] = None
                else:
                    # Anything else
                    raise ImproperlyConfigured(_INCORRECT_ARGS)
        return self._roles_dict

    @property
    def choices(self):

        return [(role, role) for role in self.roles_dict.keys()]

    def __init__(self, config=None):

        self._config = config or getattr(settings, 'USER_ROLES', ())

    def __getattr__(self, name):

        if name in self.roles_dict.keys():
            return Role(name=name)
        else:
            raise AttributeError("No such role exists '%s'" % name)

roles = Roles()

我无法找出引发此错误的原因。任何人都可以帮忙。让我用这个添加回溯,

环境:

Request Method: GET
Request URL: http://127.0.0.1:8000/en-gb/spaces/bithin/proposal/add/


Traceback:

  48. class AddProposal(FormView):
File "/home/bithin/gsoc/week3/e-cidadania/src/apps/ecidadania/proposals/views.py" in AddProposal
  78.     @m_role_required(roles.space_admin)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _dec
  34.         update_wrapper(_wrapper, func)
File "/usr/lib/python2.7/functools.py" in update_wrapper
  33.         setattr(wrapper, attr, getattr(wrapped, attr))

Exception Type: AttributeError at /en-gb/spaces/bithin/proposal/add/
Exception Value: 'Role' object has no attribute '__name__'

【问题讨论】:

  • 请发布完整的回溯,包括行号。在您确切知道是什么代码导致它之前,您无法调试该问题。异常不是由“类”引发的,而是由单独的代码行引发的。
  • Role 类在哪里?也许这只是一个错字?
  • 从apps.thirdparty.userroles导入角色的userrole中的角色类
  • 问题似乎出在role_required 装饰器中,您没有发布其代码。请尽量减少您的帖子,以包含与错误相关的代码,而不是一堆无关的代码。

标签: python django django-views django-generic-views


【解决方案1】:

查看django.utils.decorators.method_decorator 的代码。它返回的方法装饰器不能接受其他参数,除了要装饰的实际函数。此函数的属性,包括其__name__,通过functools.update_wrapper 以通常的Python 方式复制。您收到此错误是因为您传递了 Role 对象而不是函数。

换句话说,你需要像这样重写你的视图:

space_admin_required = method_decorator(role_required(roles.space_admin))
class AddProposal(FormView):

    @space_admin_required
    def dispatch(self, *args, **kwargs):
        return super(AddProposal, self).dispatch(*args, **kwargs)

【讨论】:

    【解决方案2】:

    这是Why do python instances have no __name__ attribute?的潜在副本

    简短回答:类的名称存储在类中,不能直接用于实例。 您可以通过myinstance.__class__.__name__访问实例的类名。

    【讨论】:

    • 那篇文章是关于装饰者的期望,而不是关于类的字典。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 2014-10-02
    • 2019-11-13
    • 2021-02-08
    • 2016-12-07
    • 1970-01-01
    相关资源
    最近更新 更多