我是Django的新手,并且正在构建使用REST API的Django应用程序。我有一个节流类,我想限制用户在一分钟内向同一用户发送5个以上的邀请。我发送带有URL的用户ID。
我应该访问pk才能将其用于缓存操作。如何从油门类访问pk?
例如:api / users / 3299143165471965406 / resend-invitation-email /
PK为:3299143165471965406
views.py
@decorators.action(methods=['post'], detail=True, serializer_class=None,
permission_classes=[core_permissions.IsCompanyAdmin],
url_path='resend-invitation-email', throttle_classes=[throttles.ResendInvitationThrottle])
def resend_invitation_email(self, request, pk=None):
user = get_object_or_404(User, pk=pk)
if user.invitation_status == User.INVITATION_STATUS_ACCEPTED or user.invitation_status is None:
raise ValidationError("This user is already registered.")
else:
invitations_tasks.send_invitation_email.delay(pk)
return response.Response(status=200)
油门:
class ResendInvitationThrottle(SimpleRateThrottle):
scope = 'invitation'
def get_cache_key(self, request, view):
invited_user_id = 1 # Here I should use PK
return self.cache_format % {
'scope': self.scope,
'ident': invited_user_id
}
编辑:
我通过使用
解决了该问题invited_user_id = view.kwargs['pk']