[英]Django web application handling post requests
我是 Django 的新手,對處理對我的服務器的 post 請求感到困惑。 我想接受這種 json 格式的 post 請求: {“username”:”john@doe.com”,”password”:”pass@word1”}
並用這些 json 格式的回復回復:
{“status”:”success”,”message”:”user_authed”}
如果找到用戶和密碼組合{“status”:”failure”,”message”:”user_not_found”}
如果用戶和密碼組合未找到成立
這是我的 views.py 代碼
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)
我想知道如何格式化 post 函數以接受上述格式的請求,以及如何自定義回復是否通過身份驗證。 任何幫助將不勝感激
您嘗試完成的操作稱為身份驗證。 請提前閱讀https://www.django-rest-framework.org/api-guide/authentication/ 。
然后根據所學內容編輯您的問題。
希望早日收到你的消息!
#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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.