Django signals机制的几个简单问题

1、Django signals机制不是异步执行,是同步执行,所以需要异步执行的耗时任务不能用这个。

2、异步耗时任务不用这个,那些用signals?主要是解耦那些多次重复场合被调用的函数。直接用事件挂钩的方式被调用,这可以让你的代码更干净。

4、异步耗时任务应该用什么,现在Django新出channels机制,那些可靠性要求不是100%的异步任务用这个就行了。

5、signals机制可能导致嵌套调用无限制循环,这个挂钩函数注册的信号事件,在函数内部绝对不能发生,否则就是无限制嵌套调用终致报错。

6、内建的那些事件是比较简单的,某些业务处理事件最好自己自定义signals,当然了,前提是事件操作场景多,关注这个事件的业务挂钩函数页够多才行。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Django signals are a way to allow decoupled applications to get notified when certain actions occur elsewhere in the application. Signals are used to provide a way for different components of an application to communicate with each other without being tightly coupled. In Django, signals are dispatched by senders and received by receivers. A sender is typically an instance of a particular model class, and a receiver is a function that gets executed whenever the signal is sent. Signals can be created for various events, such as when an object is saved, deleted, or when a user logs in or logs out. To use signals in Django, you need to define a receiver function and connect it to the appropriate signal. This can be done in the `signals.py` file of your Django app. Here's an example: ```python from django.db.models.signals import post_save from django.dispatch import receiver from myapp.models import MyModel @receiver(post_save, sender=MyModel) def my_receiver(sender, instance, created, **kwargs): # Do something when MyModel instance is saved if created: print("A new MyModel instance has been created!") else: print("A MyModel instance has been updated!") ``` In this example, the `my_receiver` function is decorated with the `@receiver` decorator, which connects it to the `post_save` signal of the `MyModel` class. The receiver function receives the sender (the `MyModel` class), the instance of the model being saved, and the `created` argument which indicates whether a new instance was created or an existing one was updated. By connecting receivers to signals, you can perform additional actions or trigger certain behaviors whenever specific events occur in your Django application.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值