In my last post, I built a quick Django application for posting messages, and updating those messages using the Ajax Push Engine (APE). One of the things that bugged me about the design was that the APE update occurred directly in the view that saved the message. That’s fine for the very narrow application as it stands, but what happens if sometime in the future, some other view or method saves messages? You’ll have to duplicate that APE code there too, and duplication is something we want to avoid.
All we really want to do is make sure that whenever Django saves a message, it also spits that message out to any clients listening on the APE channel. Django provides a really easy way to do that with signals. Because I’m lazy, I’ll let the Django docs describe signals to you.
So, this is _really_ easy to implement. You just define the signal handler, then connect it to the post_save signal of the Message model. Like so:
You can just stick that at the bottom of models.py if you’d like.
Now your view for handling message submission is really simple:
And there you have it… Any time you save a message, Django will tell APE, and you can forget all about it.