简体   繁体   中英

Django web application handling post requests

I am new to Django and am confused on handling post requests to my server. I want to accept post requests in this json format: {“username”:”john@doe.com”,”password”:”pass@word1”} and to reply with these json formated responses:

{“status”:”success”,”message”:”user_authed”} if the user and password combination is found {“status”:”failure”,”message”:”user_not_found”} if the user and password combination is not found

This is my views.py code

from django.shortcuts import render

from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from . models import users
from . serializers import userSerializer


class userList(APIView):

def get(self, request):
    user = users.objects.all()
    serializer = userSerializer(user, many=True)
    return Response(serializer.data)

def post(self, request):
    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)

I want to know how I can format the post function to accept requests in the format above and how to customize the reply as authenticated or not. Any help would be appreciated with this

What you are trying to accomplish is called authentication. Please readhttps://www.django-rest-framework.org/api-guide/authentication/ in advance.

Then edit your question according to what you learn.

Hope to hear from you soon!

#serializers.py
from rest_framework import serializers
UserRequestSerializer(serializers.Serializer)
    username = CharField(required=True, max_length=128)
    password = CharField(required=True, max_length=128)

#views.py
from .serializers import *

UserCheckView(APIView):

    def post(request, *args, **kwargs):
        serializer = UserRequestSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        try:
            user = User.objects.get(username=serializer.validated_data['username'])
            if user.check_password(serializer.validated_data['password']:
                return Response(data={“status”:”success”,”message”:”user_authed”},status=status.HTTP_200_OK)
            return Response(data={“status”:”failure”,”message”:”password_did_not_match”}, status=status.HTTP_400_BAD_REQUEST)
        except User.DoesNotExist:
            return Response(data={“status”:”failure”,”message”:”user_not_found”}, status=status.HTTP_404_NOT_FOUND)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM