【问题标题】:'type' object is not iterable with Django Rest Framework and django oauth2-toolkit'type' 对象不可使用 Django Rest Framework 和 django oauth2-toolkit 进行迭代
【发布时间】:2018-10-03 17:10:52
【问题描述】:

我正在尝试使用视图中的自定义身份验证类为登录用户创建新的访问令牌。

序列化器.py

class UserCreateSerializer(ModelSerializer):            

    def create(self, validated_data):
        user = User.objects.create_user(validated_data['username'], 
            validated_data['email'],
            validated_data['password'])
        return user

    class Meta:
        model = User
        fields = ('username', 'email' ,'password')

views.py

class User_Create_view(CreateAPIView):
    serializer_class = UserCreateSerializer
    queryset = User.objects.all()
    permission_classes = [AllowAny]
    authentication_classes = Has_Access_Token

    def create(self, request):
        serializers =self.serializer_class(data=request.data)
        if serializers.is_valid():
        # pdb.set_trace()
            serializers.save()   
            # Has_Access_Token.access_token(Has_Access_Token())         
            return Response(serializers.data)
        return Response(status=status.HTTP_202_ACCEPTED))

permission.py

class Has_Access_Token(BaseAuthentication):
    def access_token(self):
        app = Application.objects.get(name="testing")
        tok = generate_token()
        pdb.set_trace()
        acce_token=AccessToken.objects.get_or_create(
        user=User.objects.all().last(),
        application=app,
        expires=datetime.datetime.now() + datetime.timedelta(days=365),
        token=tok)
        return acce_token

    @method_decorator(access_token)
    def authenticate(self):
        return request

如果我使用装饰器

文件“/usr/lib/python2.7/functools.py”,第 33 行,在 update_wrapper 中 setattr(包装器,attr,getattr(包装,attr)) AttributeError: 'tuple' 对象没有属性 'module'

如果我不使用装饰器 文件“/home/allwin/Desktop/response/env/local/lib/python2.7/site-packages/rest_framework/views.py”,第 262 行,在 get_authenticators return [auth() for auth in self.authentication_classes] TypeError: 'type' 对象不可迭代

我面临的问题是,当我在 serializer.save() 之后隐式使用 Has_Access_Token 功能时,在管理员中针对用户生成访问令牌,但这不是有效的方法,因此我需要覆盖视图中的自定义 authentication_class。

有人可以建议一些方法来解决这个问题,或者让我知道上面代码的装饰器更正。

提前致谢。

【问题讨论】:

    标签: django-rest-framework django-oauth


    【解决方案1】:

    settings.py 文件中设置REST_FRAMEWORK.DEFAULT_AUTHENTICATION_CLASSES 时,customAuthencationClass 必须如下所示:

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': [ # need to be list not tuple
            'CustomAuthentication',
        ],
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-07
      • 2019-05-08
      • 2016-06-30
      • 2019-09-30
      • 2018-06-09
      • 2021-11-09
      • 2018-08-19
      • 1970-01-01
      • 2021-07-04
      相关资源
      最近更新 更多