我有两个独立的端点,分别“接受”和“拒绝”系统上的每个申请人。
端点#1:
...api/v1/applicants/{ID}/accept
端点#2:
...api/v1/applicants/{ID}/decline
现在,我正在重构并尝试将 Endpoints 合并为一个,这样可以使用以下 URL accept 和 decline 申请人,同时保持:
...api/v1/applicants/{ID}/
这样做的目的是使端点符合 REST 方法。
我尝试了什么:
我尝试创建一个隐藏方法 [以下划线开头 - 例如:_someFunction() 使用 PUT 请求方法]。这没有用。
我知道我也可以通过 serializers.py 文件来完成,但我不知道如何操作,因为我没有在网上看到示例。
这是 accept 类。 下降类似,只是有一些小的变化:
@action(detail=True, methods=['put'])
def accept(self, request, pk):
data = request.data
if request.user.user_type == "2":
if Applicant.objects.filter(id=pk).exists():
applicant = Applicant.objects.get(id=pk)
if applicant.status == '1':
applicant.status = '2'
applicant.save()
# Hash the ID of the particular applicant so it can be used for verification
# make this a function during refactoring
hashids = Hashids(salt=HASH_SALT, min_length=16)
hashid = hashids.encode(applicant.id)
# send email with the link to the applicant
# make this a function too
SENDER="xxx@example.com"
SUBJECT="Congratulations, you've been accepted!"
MESSAGE = """
Hello {}, \n
Your application as a Journalist on example.com was accepted.\n
Copy your OTP: {} and Click here "https://example.com/verify-otp/ to enter it.\n
Cheers!
""".format(applicant.first_name, hashid)
send_mail(SUBJECT, MESSAGE, SENDER, [applicant.email], fail_silently=False)
# generate a response object
queryset = applicant
serializer = ApplicantSerializer(queryset)
return Response(jsend.success({'applicants':serializer.data}))
else:
return Response((jsend.error("Cannot perform such action for this applicant")), status=status.HTTP_400_BAD_REQUEST)
else:
return Response((jsend.error('Cannot find an applicant with ID of {}'.format(pk))), status=status.HTTP_404_NOT_FOUND)
else:
return Response((jsend.error("You are not authorized to perform this action")), status=status.HTTP_403_FORBIDDEN)
最佳答案
例如,您可以使用 perform_update 覆盖 ModelViewSet 的 perform_update() 或 update():
def perform_update(self, serializer):
applicant = self.get_object()
if applicant.status == '1':
serializer.save(status='2')
#rest of your logic
serializer.save()
希望对您有所帮助。请注意,您可以像这样在 perform_update 中获取请求:
self.request
关于python - 将方法添加到 ModelViewset Endpoint,而无需调用 URL 中的方法名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52485203/