#django-rest-framework
#django-rest-framework
Вопрос:
Я пытался использовать декоратор аутентификации, но он не сработал, здесь следует мой код
class UserViewSet(CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin, GenericViewSet):
print('enter')
queryset = UserProfile.objects.all()
@authentication_classes([JwtAuthorizationAuthentication,])
def create(self, request, *args, **kwargs):
print('creat')
print(request.query_params)
return ('ok')
def retrieve(self, request, *args, **kwargs):
print(f'1{self.authentication_classes}')
print('ok2')
return Response('ok')
Я просто хочу использовать JWTAuthentication только при использовании действий создания и обновления, и больше никакой аутентификации для других действий в наборе представлений.
И я также пытаюсь написать декораторы для решения проблемы, но auth_decorator не работает
from functools import update_wrapper
def auth_wrapper(*authentications, validate_auth=True):
def decorator(func):
def wrapper(self, request, *args, **kwargs):
self.authentication_classes=authentications
print(self.authentication_classes)
if validate_auth:
print(f'request1:{request.user}')
self.perform_authentication(request)
print(f'request2:{request._user}')
# print(type(self.perform_authentication(request)))
return func(self, request, *args, **kwargs)
return update_wrapper(wrapper, func)
return decorator
def permission_wrapper(*permissions, validate_perm=True):
def decorator(func):
def wapper(self, request, *args, **kwargs):
self.permission_classes=permissions
if validate_perm:
self.check_permissions(request)
return func(self, request, *args, **kwargs)
return update_wrapper(wapper, func)
return decorator
Кто-нибудь может помочь мне решить проблему? Спасибо
Ответ №1:
def get_authenticators(self):
if is_post_method(post):
return [JwtAuthorizationAuthentication,]
return super().get_authenticators()
Я решаю проблему с помощью приведенного выше кода