gpt4 book ai didi

python - POST 或 GET 失败或成功时友好的返回消息

转载 作者:行者123 更新时间:2023-12-01 09:32:45 25 4
gpt4 key购买 nike

当 GET 或 POST 成功或失败时,如何向客户端返回友好消息?

序列化器.py

class BrandSerializer(serializers.ModelSerializer):
"""
Class to serialize Brand objects
"""
class Meta:
model = Brand
fields = '__all__'
read_only_fields = 'id'

class BrandSignupSerializer(serializers.Serializer):
"""
Create Brand profile
"""
name = serializers.CharField(required=True, write_only=True)
brand = serializers.CharField(required=True, write_only=True)
email = serializers.EmailField(required=True, write_only=True)
phone = serializers.CharField(required=True, write_only=True)
website = serializers.CharField(required=True, write_only=True)

class Meta:
model = Brand
fields = ('name', 'brand', 'email', 'phone', 'website')
unique = 'email'

def create(self, validated_data):
brand = Brand.objects.create(**validated_data)
brand.save()
return brand

def update(self, instance, validated_data):
pass

views.py

class BrandList(generics.ListAPIView):
"""
List all Brands
HTTP: GET
"""
queryset = Brand.objects.all()
serializer_class = BrandSerializer


class BrandDetail(generics.RetrieveUpdateDestroyAPIView):
"""
List one Brand
HTTP: GET
"""
queryset = Brand.objects.all()
serializer_class = BrandSerializer

class BrandSignup(generics.CreateAPIView):
"""
Brand signup
HTTP POST
"""
queryset = Brand.objects.all()
serializer_class = BrandSignupSerializer

def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)

def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
return Response(data=serializer.data, status=status.HTTP_201_CREATED)

最佳答案

我相信您可以在 Response 中传递一个字典,您可以在其中插入自定义信息,例如序列化器数据、自定义消息、状态和状态代码作为字符串:

def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if (serializer.is_valid(raise_exception=True)) :
response_details = {
'data': serializer.data,
'message': "Your custom success message",
'code': "201",
'status': HTTP_201_CREATED
}
else :
response_details = {
'data': serializer.errors,
'message': "Your custom error message",
'code': "400",
'status': HTTP_400_BAD_REQUEST
}
return Response(response_details, status=response_details['status'])

然后,您可以在渲染数据的 View 中访问随响应一起传递的字典的不同元素,例如 datamessage

关于python - POST 或 GET 失败或成功时友好的返回消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49817397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com