Python: 运行 return 之后的代码
Python: Run a code after return something
这是我的 django 项目中的 ApiView:
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})
如您所见,如果 client.is_busy
不是 True
,我将其设为 True
。但是在这种情况下,我需要在 30 秒后 client.is_busy = False
。如果我在 client.save()
代码下执行此操作,它会延迟响应。我该怎么做?
不要使用布尔值来确定客户端是否忙碌,而是使用日期时间,如果它在 30 秒前设置,则客户端忙碌。这意味着您不需要 运行 请求后的任何代码
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()
你应该考虑在这里使用计时器对象。
例如
import threading
def free_up_client(client):
client.is_busy = false
timer = Theading.timer(30.0, free_up_client, [client])
这是我的 django 项目中的 ApiView:
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})
如您所见,如果 client.is_busy
不是 True
,我将其设为 True
。但是在这种情况下,我需要在 30 秒后 client.is_busy = False
。如果我在 client.save()
代码下执行此操作,它会延迟响应。我该怎么做?
不要使用布尔值来确定客户端是否忙碌,而是使用日期时间,如果它在 30 秒前设置,则客户端忙碌。这意味着您不需要 运行 请求后的任何代码
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()
你应该考虑在这里使用计时器对象。
例如
import threading
def free_up_client(client):
client.is_busy = false
timer = Theading.timer(30.0, free_up_client, [client])