Example #1
0
 def post(self, request, format=None):
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     else:
         raise ValidationError()
Example #2
0
 def put(self, request, pk, format=None):
     user = self.get_object(pk)
     serializer = UserSerializer(user, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #3
0
 def put(self, request, pk, format=None):
     user = self.get_object(pk)
     serializer = UserSerializer(user, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #4
0
    def getByUsername(self, request, username ):
        user = get_object_or_404(User, username=username)
        
        serializer_context = {
            'request': request,
        }

        return Response(UserSerializer(user, context=serializer_context).data, status=status.HTTP_200_OK)
Example #5
0
def user_detail(request, pk):
    serializer_context = {
        'request': request,
    }
    try:
        user = User.objects.get(pk=pk)
    except User.DoesNotExist:
        return JsonResponse({'message': 'The user does not exist'},
                            status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        user_serializer = UserSerializer(user, context=serializer_context)
        return JsonResponse(user_serializer.data)

    elif request.method == 'PUT':
        user_data = JSONParser().parse(request)
        user_serializer = UserSerializer(user,
                                         data=user_data,
                                         context=serializer_context)
        if user_serializer.is_valid():
            user_serializer.save()
            return JsonResponse(user_serializer.data)
        return JsonResponse(user_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        user.delete()
        return JsonResponse({'message': 'User was deleted successfully!'},
                            status=status.HTTP_204_NO_CONTENT)
Example #6
0
 def get(self, request, format=None):
     users = User.objects.all()
     serializer = UserSerializer(users, many=True)
     # counter = metricsRegistry.counter("GET_called")
     # counter.inc()
     # g = graphitesend.init(prefix='test', system_name='', graphite_server='ec2-52-26-169-20.us-west-2.compute.amazonaws.com')
     # g.send('count', counter.get_count())
     #print(counter("get_calls").get_count())
     return Response(serializer.data)
Example #7
0
def user_all_list(request):
    users = User.objects.filter(published=True)
    serializer_context = {
        'request': request,
    }
    if request.method == 'GET':
        users_serializer = UserSerializer(users,
                                          many=True,
                                          context=serializer_context)
        return JsonResponse(users_serializer.data, safe=False)
Example #8
0
 def post(self, request, *args, **kwargs):
     username = request.data.get("username", "")
     password = request.data.get("password", "")
     email = request.data.get("email", "")
     if not username and not password and not email:
         return Response(
             data={
                 "message": "username, password and email is required to register a user"
             },
             status=status.HTTP_400_BAD_REQUEST
         )
     new_user = User.objects.create_user(
         username=username, password=password, email=email
     )
     return Response(
         data=UserSerializer(new_user).data,
         status=status.HTTP_201_CREATED
     )
Example #9
0
def user_detail(request, pk):
    """
    获取,更新或删除一个 code user。
    """
    try:
        user = User.objects.get(pk=pk)
    except User.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = UserSerializer(user)
        return JSONResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = UserSerializer(user, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        user.delete()
        return HttpResponse(status=204)
Example #10
0
def user_list(request):
    serializer_context = {
        'request': request,
    }
    if request.method == 'GET':
        users = User.objects.all()

        title = request.query_params.get('title', None)
        if title is not None:
            users = users.filter(title__icontains=title)

        users_serializer = UserSerializer(users,
                                          many=True,
                                          context=serializer_context)
        return JsonResponse(users_serializer.data, safe=False)
        # 'safe=False' for objects serialization

    elif request.method == 'POST':
        user_data = JSONParser().parse(request)
        user_serializer = UserSerializer(data=user_data,
                                         context=serializer_context)
        if user_serializer.is_valid():
            user_serializer.save()
            return JsonResponse(user_serializer.data,
                                status=status.HTTP_201_CREATED)
        return JsonResponse(user_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        count = User.objects.all().delete()
        return JsonResponse(
            {
                'message': '{} Users were deleted successfully!'.format(
                    count[0])
            },
            status=status.HTTP_204_NO_CONTENT)
Example #11
0
 def post(self, request, format=None):
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #12
0
    def retrieve(self, request, pk=None):
        queryset = User.objects.all()
        user = get_object_or_404(queryset, pk=pk)
        serializer = UserSerializer(user)

        return Response(serializer.data)
Example #13
0
 def get(self, request, format=None):
     users = User.objects.all()
     serializer = UserSerializer(users, many=True, context={'request': request})
     return Response(serializer.data)
Example #14
0
 def post(self, request, format=None):
     serializer = UserSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #15
0
 def get(self, request, pk, format=None):
     user = self.get_object(pk)
     user = UserSerializer(user)
     return Response(user.data)
Example #16
0
    def list(self, request):
        queryset = User.objects.all()
        serializer = UserSerializer(queryset, many=True)

        return Response(serializer.data)
Example #17
0
    def create(self, request):  # crestinga valid using user using POST
        data = json.loads(request.body)
        print(request.META)
        # AnonymousUser(it means the rest framework auth still do not recognises it)
        print(request.user)
        # print(request.body)#b'{\n    "username":"******",\n    "email":"*****@*****.**",\n    "password":"******"\n\n}'
        if data["type_request"] == "create":
            # print(request)#<rest_framework.request.Request: POST '/new-api/'>
            serializer = UserSerializer(data=data)
            # print(serializer)
            #     UserSerializer(data={'username': '******', 'email': '*****@*****.**', 'password': '******'}):
            # username = CharField(help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, validators=[<django.contrib.auth.validators.UnicodeUsernameValidator object>, <UniqueValidator(queryset=User.objects.all())>])
            # email = EmailField(allow_blank=True, label='Email address', max_length=254, required=False)
            # password = CharField(max_length=128)
            if serializer.is_valid():
                user = serializer.save()
                user.set_password(data["password"])
                token = Token.objects.create(user=user)
                print(token.key)  # fb7f6bd1d90940efb58152f08efd883b7cbd4826
                # HTTP_AUTHORIZATION': 'Token f147069a2f2a9dc55e492362d239db35cb8ae008'
                # (status code generated is 201)
                return JsonResponse(
                    {
                        "user":
                        UserSerializer(
                            user, context=self.get_serializer_context()).data
                    },
                    safe=False)
            else:
                return JsonResponse(serializer.errors, safe=False)
        if data["type_request"] == "login":
            status = authenticate(username=data["username"],
                                  password=data["password"])
            print(status)
            user = User.objects.get(username=data["username"])
            print(user)  # shivansh.1923cs1076
            if user is not None:
                response = login(request, user)  # null
                print(user.is_authenticated)  # True
                # <django.contrib.sessions.backends.db.SessionStore object at 0x7f0c082f5e80>
                print(request.session)
                # print(request.META['HTTP_COOKIE'])#sessionid=ky8pp6z1p0m6znxtxq5efpllpe6wsnb0   (after successful login only this cookie is generated and for the same ssession that is until logout the sessionid remains the same )
                permission_classes = [permissions.IsAuthenticated]
                print(permission_classes)
                return JsonResponse(response, safe=False)
            else:
                return JsonResponse("nope", safe=False)
        if data["type_request"] == "logout":
            status = authenticate(username=data["username"],
                                  password=data["password"])
            print(status)
            user = User.objects.get(username=data["username"])
            print(user)
            if user is not None:
                response = logout(request)  # null
                print(user.is_authenticated)  # True
                # <django.contrib.sessions.backends.db.SessionStore object at 0x7f0c082f5e80>
                print(request.session)
                # print(request.META['HTTP_COOKIE'])#sessionid=ky8pp6z1p0m6znxtxq5efpllpe6wsnb0
                return JsonResponse(response, safe=False)
            else:
                return JsonResponse("nope", safe=False)
            # here we need not to check EXISTS as DRF does this with the auth sys if a duplicate entry is given:(serializer.errors)
            # {
            #    "username": [
            #    "A user with that username already exists."
            #       ]
            # }##this error is raised(DRF DIFFERENTIATES BETWEEN USEERS WITH THEIR USERNAME ONLY!!!! WHICH IS THE ONLY RESONABLE THING )


# RESPONSE ATER SUCCESFULL CREATION############################3
# {
#   user": {
#         "username": "******",
#         "email": "*****@*****.**",
#         "password": "******"
#          }
#
        if data["type_request"] == "session_authentication":
            authentication_classes = (SessionAuthentication, )
            # permission_classes = (IsAuthenticated,)
            status = authenticate(username=data["username"],
                                  password=data["password"])
            print(status)
            user = User.objects.get(username=data["username"])
            print(user)  # shivansh.1923cs1076
            if user is not None:
                response = login(request, user)  # null
                print(user.is_authenticated)  # True
                # <django.contrib.sessions.backends.db.SessionStore object at 0x7f0c082f5e80>
                print(request.session)
                # print(request.META['HTTP_COOKIE'])#sessionid=ky8pp6z1p0m6znxtxq5efpllpe6wsnb0   (after successful login only this cookie is generated and for the same ssession that is until logout the sessionid remains the same )
                permission_classes = [permissions.IsAuthenticated]
                print(permission_classes)
                return JsonResponse(response, safe=False)
            else:
                return JsonResponse("nope", safe=False)