You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

代码行if group in allowed_users出现‘argument of type 'function' is not iterable’错误排查

错误分析与解决:argument of type 'function' is not iterable

错误原因

代码里if group in allowed_users:这一行犯了命名混淆的错误:这里的allowed_users是你定义的外层装饰器函数本身,而非传入的允许角色列表参数。函数属于不可迭代类型,用in判断成员自然会抛出argument of type 'function' is not iterable错误。

另外还有个隐藏陷阱:用空列表[]作为装饰器的默认参数,Python中可变默认参数会被所有装饰器实例共享,后续调用如果不指定allowed_roles,会导致之前添加的角色残留,引发权限逻辑混乱。

修复后的代码

from django.http import HttpResponse

def allowed_users(allowed_roles=None):
    # 修复可变默认参数的陷阱
    if allowed_roles is None:
        allowed_roles = []
    def decorator(view_func):
        def wrapper_func(request, *args, **kwargs):
            group = None
            if request.user.groups.exists():
                group = request.user.groups.all()[0].name
            
            # 引用正确的允许角色列表参数
            if group in allowed_roles:
                return view_func(request, *args, **kwargs)
            else:
                return HttpResponse('You are not authorized to view this Page')
        return wrapper_func
    return decorator

关键修改点

  • 将判断条件里的allowed_users替换为allowed_roles,确保引用的是传入的允许角色列表
  • 把默认参数allowed_roles=[]改成allowed_roles=None,并在函数内部初始化空列表,避免可变默认参数的共享问题

内容的提问来源于stack exchange,提问作者Ashray Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 02:35:19