简体   繁体   English

一次停止运行一次以上的Django Model函数

[英]Stopping a Django Model function being run more than once, at once

I have a Django Model class for a booking slot. 我有一个预订舱位的Django模型类。 Once we have all the auxiliary data and payment is ready to be made, we get a live availability and allocate a booking. 有了所有辅助数据并准备好付款后,我们就会获得实时可用性并分配预订。 This whole last step of the process takes a couple of seconds (mostly waiting on the payment provider to clear). 该过程的整个最后一步需要花费几秒钟的时间(主要是等待付款提供商清算)。 In theory two payments coming through at once could double-book a slot. 理论上讲 ,一次完成两次付款可以使一个位预定两次。

That's all handled by a single function Booking.book() . 全部由单个函数Booking.book() Is there any sane way I can limit so that only one instance can work at once and others are queued? 有什么我可以限制的明智方法,以便只有一个实例可以同时工作而其他实例却处于排队状态?

The deployment design is initially pretty simple but there could be scale to multiple servers eventually. 部署设计最初非常简单,但是最终可以扩展到多个服务器。

What's the proper way of doing this and what are its downsides? 这样做的正确方法是什么,它的缺点是什么?

What you can do is lock the slot for the booking once the payment is initiated. 您可以做的就是在付款后锁定用于预订的位置。 That way you only "lose" availability for a few moments. 这样一来,您只会“失去”一会儿。 The lock can be done on the same centralized system that holds the rest of the information. 可以在保存其余信息的同一集中式系统上完成锁定。 For instance you can scale up the application servers but keep a single entry point to the data source. 例如,您可以扩展应用程序服务器,但保留数据源的单个入口点。 You release the lock once the payment is declined or confirm. 付款被拒绝或确认后,您将释放锁。

You could add a foreignkey to your products like this : 您可以像这样向产品添加外键:

class Reservation(models.Model):
    reservations = ForeignKey(Book)
    quantity = models.IntegerField(default=0)
    creation = models.DateTimeField(auto_now_add)
    user = ForeignKey(User)

class Book(models.Model):
    ...

Whenever someone is ready for a payment, you add a Reservation per book type, and reduce your Book.stock by the quantity (for this part, you could also have a "reserved" column if you prefer, or calculate the available quantity using joins but this last would'nt be very efficient). 每当有人准备付款时,您都可以为每种图书类型添加一个“预定”,并按数量减少Book.stock(对于此部分,如果您愿意,也可以有一个“保留”列,或者使用联接来计算可用数量但最后一个效率不高)。

If the payment is validated, you only have to remove the Reservation entries, and if it is not, put back your stock. 如果付款经过验证,则只需删除“保留”条目,否则,请放回库存。 You could have a cron every few minutes that would get the stocks back if the reservation is expired (using the creation field). 您可能每隔几分钟就有一次Cron,如果预订过期(使用创建字段),这将使库存退还。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM