处理成功和失败的响应Django



用户正在向crate order发送一个api请求以及请求体中的信息,保存数据后,我将向用户返回order_id和access_token。我在使用model.full_clean((时也使用了一些身份验证。现在我只能返回成功和失败状态代码和消息以及order_id和access_token。

@api_view(['POST'])
def orderdetails(request):  
try:
ACCESS_KEY_ID = request.META.get('HTTP_ACCESS_KEY_ID')
ACCESS_KEY_SECRET = request.META.get('HTTP_ACCESS_KEY_SECRET')
applications = Applications.objects.all()
id=0
for e in applications:
if(e.ACCESS_KEY_ID==ACCESS_KEY_ID and e.ACCESS_KEY_SECRET==ACCESS_KEY_SECRET ):
id = e.id+id
print(id)
break
else:
return Response({"Message":"Enter Valid Credentials"})
except ValueError:
return Response({"ACCESS":"DENIED"})


if request.method == 'POST':       
data=request.data
print(data)
orders = Orders(applications=Applications.objects.get(id=id),
purpose_code = data['purpose_code'],
amount=data['amount'],
currency=data['currency'],
note=data['note'],
payer_name=data['payer_name'],
payer_email=data['payer_email'],
payer_phone_country_code=data['payer_phone_country_code'],
payer_phone_number=data['payer_phone_number'],
payee_name=data['payee_name'],
payee_email=data['payee_email'],
payee_phone_country_code=data['payee_phone_country_code'],
payee_phone_number=data['payee_phone_number'],
payee_pan = data['payee_pan'],
payee_bank_account_holder_name=data['payee_bank_account_holder_name'],
payee_bank_account_number=data['payee_bank_account_number'],
payee_bank_account_ifsc=data['payee_bank_account_ifsc'],
payee_bank_account_type=data['payee_bank_account_type'],
payee_bank_account_beneficiary_identifier=data['payee_bank_account_beneficiary_identifier'],
payment_collection_webhook_url=data['payment_collection_webhook_url'],
payment_transfer_webhook_url=data['payment_transfer_webhook_url'],
payment_gateway_code = data['payment_gateway_code'],
isActive=data['isActive']
)
try:
orders.full_clean()
except ValidationError:
return Response({"Error message":"invalid request body"})

else:
orders.save()
serializer = OrderSerializer(orders)
order_id = serializer.data['id']
access_token = serializer.data['access_token']
return Response({"orderId":order_id,"accessToken":access_token})

所需的成功和失败响应,格式如下:成功响应(201/202(以及order_id和access_token故障响应(422(以及消息:;错误消息内容";

您可以将状态代码传递到响应对象中,如下所示:

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['POST'])
def orderdetails(request): 
return Response({'foo':'bar'}, status=status.HTTP_200_OK)

您可以在响应中返回不同的HTTP状态代码。

# Importing status
from rest_framework import status
# To return a Successful response
# content is the data you return in the response, in your case its
content = {"orderId":order_id,"accessToken":access_token}
return Response(content, status=status.HTTP_200_OK)

# To return a Bad Request response
content = {"Error message":"invalid request body"}
return Response(content, status=status.HTTP_400_BAD_REQUEST)

你可以在这里找到DRF的所有不同的HTTP状态代码

相关内容

  • 没有找到相关文章

最新更新