Wednesday, July 7, 2021

Django using Signals

Django Signals are an implementation of the Observer Pattern.


Aside from the signals dispatcher, Django also ships with some useful signals that we can listen on. They include:

  • post_save, which is sent out whenever a new Django model has been created and saved. For instance, when a user signs up or uploads a new post,
  • pre_delete, which is sent out just before a Django model is deleted. A good scenario would be when a user is deleting a message or their account,
  • request_finished, which is fired whenever Django completes serving an HTTP request. This can range from opening the website or accessing a particular resource


When to Use Signals



  • When we have many separate pieces of code interested in the same events, a signal would help distribute the event notification as opposed to us invoking all of the different pieces of code at the same point, which can get untidy and introduce bugs
  • We can also use Django signals to handle interactions between components in a decoupled system as an alternative to interaction through RESTful communication mechanisms
  • Signals are also useful when extending third-party libraries where we want to avoid modifying them, but need to add extra functionality



references

https://stackabuse.com/using-django-signals-to-simplify-and-decouple-code

No comments:

Post a Comment