0

This is an ApiView from my django project:

class Receive_Payment(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAdminUser,)
    def get(self, request, cc_number):
        if Card.objects.filter(cc_num = cc_number).exists():
            client = Client.objects.get(client_id = (Card.objects.get(cc_num = cc_number).client))
            if not client.is_busy:
                client.is_busy = True
                client.save()
                resp = "successful"
            else:
                resp = "client_is_busy"
        else:
            resp = "fail"
        return Response({"response": resp})

As you see, if client.is_busy is not True, I'm making it True in here. But in this situation, I need to client.is_busy = False after 30 seconds. If I do it under client.save() code, it delays to response. How can I do it?

2 Answers 2

3

Instead of using a boolean for determining if the client is busy, use a datetime and if it was set less than 30 seconds ago the client is busy. This then means you don't need to run any code after the request

from django.db import models
from django.utils.timezone import now
from datetime import timedelta


class Client(models.Model):
    last_updated = models.DateTimeField()

    @property
    def is_busy(self):
        # Can add a property to maintain the same is_busy boolean attribute
        return (now() - self.last_updated) < timedelta(seconds=30)

    def set_busy(self):
        self.last_updated = now()
        self.save()
Sign up to request clarification or add additional context in comments.

Comments

2

You should consider using timer objects here.

e.g.

import threading
def free_up_client(client):
   client.is_busy = false

timer = Theading.timer(30.0, free_up_client, [client])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.