apis.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from drf_spectacular.utils import extend_schema
  2. from rest_framework import serializers
  3. from rest_framework.views import APIView, Response
  4. from account import selectors, services
  5. class GetUsersView(APIView):
  6. class OutputSerializer(serializers.Serializer):
  7. id = serializers.IntegerField()
  8. email = serializers.EmailField()
  9. is_staff = serializers.BooleanField()
  10. is_active = serializers.BooleanField()
  11. class FilterSerializer(serializers.Serializer):
  12. name = serializers.CharField(required=False)
  13. @extend_schema(responses=OutputSerializer, parameters=[FilterSerializer])
  14. def get(self, request):
  15. users = selectors.get_users(self.FilterSerializer(request.query_params).data)
  16. return Response(self.OutputSerializer(users, many=True).data)
  17. get_users_view = GetUsersView.as_view()
  18. class AddUserView(APIView):
  19. class InputSerializer(serializers.Serializer):
  20. first_name = serializers.CharField()
  21. last_name = serializers.CharField()
  22. email = serializers.EmailField()
  23. is_staff = serializers.BooleanField()
  24. institution_id = serializers.CharField()
  25. class OutputSerializer(serializers.Serializer):
  26. id = serializers.IntegerField()
  27. email = serializers.EmailField()
  28. is_staff = serializers.BooleanField()
  29. is_active = serializers.BooleanField()
  30. serializer_class = InputSerializer
  31. def post(self, request):
  32. serz = self.InputSerializer(data=request.data)
  33. serz.is_valid(raise_exception=True)
  34. user = services.add_user(
  35. first_name=serz.validated_data["first_name"], # type: ignore
  36. last_name=serz.validated_data["last_name"], # type: ignore
  37. email=serz.validated_data["email"], # type: ignore
  38. is_staff=serz.validated_data["is_staff"], # type: ignore
  39. institution_id=serz.validated_data["institution_id"], # type: ignore
  40. )
  41. return Response(self.OutputSerializer(user).data)
  42. add_user_view = AddUserView.as_view()