简体   繁体   中英

django custom signals vs regular functions

I started to learn on django signal feature when I wanted to run a method only when a certain event has occurred.

So I read about custom signals and I couldn't find a reason to use signals over regular functions calls.

I read in the django Guide about how to call a signal:

The signal

pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])

The call:

def send_pizza(self, toppings, size):
    pizza_done.send(sender=self.__class__, toppings=toppings, size=size)

and i can't understand how they are different. Then I just call directly to the receiver function...

Can someone enlighten me about it?

You can think of signals as an implementation of observer design pattern .

It's propose is to remove the dependencies from observable to observer. So observable know nothing about the observer.

Like saving a model ( post_save and pre_save signals). You could face cases you need YourModel.save method not to know about that a task should be done after/before saving.

Django default signals are a good sample. But I don't think you will need to create custom signal everyday (nor every project!).

And I suggest that you shouldn't use signals (default signals and custom signals) until you really need them, make them the last choice. As they can make your code hard to read, as reader can't figure out easily where are your logic.

Django before 1.7 doesn't have a convention for where to place your signals receivers. In django >= 1.7 you should use AppConfig .ready to connect the receivers.

Django signals are the implementation of the publish-subscribe design pattern . They allows you to decouple the different parts of the project. For example when you develop the "make pizza" app you don't have to know anything about "delivery pizza" app.

Another great example of this pattern - django built-in pre_save / post_save signal. You can add any logic to this event at any time without modifying of the django core.

Widely used scenario is to add user profile info after creating user instance. You just add the listener to post_save(sender=User) event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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