[英]Add method to ModelViewset Endpoint without having to call the method name in the URL
我有兩個單獨的端點,分別“接受”和“拒絕”系統上的每個申請人。
端點#1:
...api/v1/applicants/{ID}/accept
端點#2:
...api/v1/applicants/{ID}/decline
現在,我正在重構並嘗試將端點合並為一個,以便可以使用以下 URL接受和拒絕申請人,同時保持:
...api/v1/applicants/{ID}/
這樣做的目的是使端點符合 REST 方法。
我試過的:
我嘗試創建一個隱藏的方法 [以下划線開頭 - 例如:_someFunction() 使用 PUT 請求方法]。 這沒有用。
我知道我也可以通過serializers.py文件來做到這一點,但不知道怎么做,因為我還沒有在網上看到一個例子。
這是接受類。 下降幅度類似,但有細微的變化:
@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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.