| Version 17 (modified by , 19 years ago) ( diff ) |
|---|
What Are Signals?
Django includes an internal "dispatcher" which provides two pieces of functionality:
- Pieces of code which want to advertise what they're doing can use the dispatcher to send "signals" which contain information about what's happening.
- Pieces of code which want to do something whenever a certain event happens can use the dispatcher to "listen" for particular signals, then execute the functions they want when those signals are sent out.
The actual mechanism comes from a third-party library called PyDispatcher, which is bundled with Django and which lives at django.dispatch.dispatcher.
How signals work
A signal is just a simple Python object, and requires nothing special to set up. For example, the post_save signal, found in django.db.models.signals, is defined like so:
post_save = object()
When a piece of code wants to send a signal, it needs to do three things:
- Import the signal from wherever it's been defined.
- Import the dispatcher.
- Use the dispatcher's
sendfunction to send the signal.
An example of this can be found in the save method of the base model class, django.db.models.Model; the file in which that class is defined imports the signals defined in the django.db.models module:
from django.db.models import signals
It also imports the dispatcher:
from django.dispatch import dispatcher
And in the very last line of the save method, it sends the post_save signal:
dispatcher.send(signal=signals.post_save, sender=self.__class__, instance=self)
The first two arguments are fairly clear, and are common for all uses of the dispatcher:
signalis the signal to be sent.senderis the object which is sending the signal; in this case,self.__class__; this will be whatever model class the object which was just saved belongs to.
The third argument, instance, is one of the more interesting features of the dispatcher: when sending a signal, you are free to include any extra arguments beyond these two; if a function which is listening for the signal is expecting certain information to be passed in as arguments, the dispatcher will ensure that the extra arguments to send are used. In this case the extra argument instance is self, which means it will be the object which was just saved. This means that functions which are listening for the post_save signal can, if they want to do something with the object that was just saved, specify that they take an argument named instance, and the dispatcher will pass it to them.
To listen for a signal, first define a function that you want to execute when the signal is sent; if you know that the signal will be sent with extra arguments and you want to use those arguments, make sure your function accepts them. Then you need to do three things:
- Import the signal object you'll be listening for.
- Import the dispatcher.
- Use the dispatcher's
connectsignal to tell the dispatcher you want to listen for something.
A good example of this is found in Django's bundled "contenttypes" application, which creates and maintains a registry of all the installed models in your database. In order to do this, the contenttypes app defines a ContentType model, and it needs to know any time a new model is installed so it can create the appropriate ContentType object for that model. To do this, it includes a file called management.py; whenever manage.py syncdb is run, it loops through every application in the INSTALLED_APPS setting, and looks to see if any apps contain a module called management; if they do, manage.py imports them before installing any models, which means that any dispatcher connections listed in an app's management module will be set up before model installation happens.
In its management.py file, the contenttypes app defines a function called create_contenttypes, which takes three arguments: app, created_models and verbosity. These correspond to the extra arguments manage.py will use with dispatcher.send when it sends the post_syncdb signal after installing each new application, and provide enough information to determine which models need to have new ContentType objects created (actually, just app and created_models would be enough; the extra argument, verbosity, is used by manage.py to indicate whether any listening functions should be "verbose" and echo output to the console, or be quiet and not echo any output.
The management.py file also imports django.db.models.signals and django.dispatch.dispatcher; after the create_contenttypes function is defined, it sets up that function to listen for the post_syncdb signal:
dispatcher.connect(create_contenttypes, signal=signals.post_syncdb)
The first argument, create_contenttypes, is the name of the function to execute when the signal is sent out. The second argument, signal, is the signal to listen for. There is another optional argument, sender, which is not used in this example; sender can be used to narrow down exactly what will be listened for; when you specify sender, your function will only be executed when the object which sent the signal is the same as the object you specify as the sender argument.
An example of this can be found in Django's authentication application: django.contrib.auth.management defines a function called create_superuser, and uses the dispatcher to connect to the post_syncdb signal -- but only when post_syncdb is being sent as a result of installing the auth application. To do this, the auth app's management.py file imports its own models:
from django.contrib.auth import models as auth_app
And then uses the sender argument to dispatcher.connect:
dispatcher.connect(create_superuser, sender=auth_app, signal=signals.post_syncdb)
Here's a breakdown of exactly why that works:
- Whenever
manage.py syncdbfinishes installing the models for a particular application, it sends thepost_syncdbsignal. You'll remember thatdispatcher.sendtakes an optional argument,sender, which is the object that's "sending" the signal. In this case,manage.py syncdbsetssenderto be themodelsmodule of the app it just installed. django.contrib.auth.managementimport the auth app's models asauth_app, which means that, within that file, the variableauth_appis the moduledjango.contrib.auth.models.- So when
manage.py syncdbsend thepost_syncdbsignal withdjango.contrib.auth.modelsas thesenderargument, the dispatcher notices that this is the same as thesenderspecified in thedispatcher.connectcall indjango.contrib.auth.management, and so thecreate_superuserfunction is executed.
In case you've ever wondered, that's how Django knows to prompt you to create a superuser whenever you install the auth app for the first time. The auth app also sets up another function -- create_permissions -- which doesn't specify sender in its call to dispatcher.connect, so it runs any time post_syncdb is sent. That's how the auth app creates the add, change and delete Permission objects for each application you install.
List of signals built in to Django
Django defines several sets of signals which are used internally, and which you can listen for in order to run your own custom code at specific moments.
django.db.models.signals defines the following signals:
class_prepared
This is sent whenever a model class has been "prepared"; in other words, once most of the metaprogramming which makes models work has been completed. Django uses this signal internally to know when to generate and add the automatic AddManipulator and ChangeManipulator to a model class (see the DevModelCreation page for details).
Arguments that are sent with this signal:
sender-- the model class which was just prepared.
pre_init
Whenever you create a new instance of a Django model (for example, in the first part of the Django tutorial when you do p = Poll(question="What's up?", pub_date=datetime.now())) , this signal is sent at the beginning of the execution of the model's __init__ method. Note: if you override __init__ on your model, you must call the parent class' __init__ method for this signal to be sent, and it will be sent at the beginning of the parent class' __init__ method.
Arguments sent with this signal:
sender-- the model class you're creating an instance of.args-- a list of positional arguments passed to the model's__init__method.kwargs-- a dictionary of keyword arguments passed to the model's__init__method. For example, in the tutorial when you dop = Poll(question="What's up?", pub_date=datetime.now()), thekwargsargument to thepre_initsignal would be the dictionary{'question': "What's up?", 'pub_date': datetime.now()}.
post_init
Like pre_init, but this one is sent when the model's __init__ method is done executing. Note: if you override __init__ on your model, you must call the parent class' __init__ method for this signal to be sent, and it will be sent at the end of the parent class' __init__ method.
Arguments sent with this signal:
sender-- the model class you've just created an instance of.instance-- the instance of the model you just created. For example, in the tutorial when you dop = Poll(question="What's up?", pub_date=datetime.now()), theinstanceargument to thepost_initsignal would be thePollobject you just created.
pre_save
This is sent at the beginning of a model's save method. Note: if you override save on your model, you must call the parent class' save method for this signal to be sent, and it will be sent at the beginning of the parent class' save method.
Arguments sent with this signal:
sender-- the model class of the object being saved.instance-- the actual object being saved.
post_save
This is sent at the end of a model's save method. Note: if you override save on your model, you must call the parent class' save method for this signal to be sent, and it will be sent at the end of the parent class' save method.
Arguments sent with this signal:
sender-- the model class of the object which was just saved.instance-- the actual object which was just saved.
pre_delete
This is sent at the beginning of a model's delete method. Note: if you override delete on your model, you must call the parent class' delete method for this signal to be sent, and it will be sent at the beginning of the parent class' delete method.
Arguments sent with this signal:
sender-- the model class of the object which is about to be deleted.instance-- the actual object which is about to be deleted.
post_delete
This is sent at the end of a model's delete method. Note: if you override delete on your model, you must call the parent class' delete method for this signal to be sent, and it will be sent at the beginning of the parent class' delete method.
Arguments sent with this signal:
sender-- the model class of the object which was just deleted.instance-- the actual object which was just deleted (the object will no longer be in the database, but will stick around in memory for a little while after that).
post_syncdb
Sent by manage.py syncdb after it installs an application.
Arguments sent with this signal:
sender-- themodelsmodule of the application which was just installed.app-- same assender.created_models-- a list of the model classes whichmanage.pyhas created so far, regardless of app.verbosity-- indicates how much informationmanage.pyis printing on screen. There are three possible values: 0 means no information, 1 means some information and 2 means all possible information. Functions which listen for this signal should adjust what they output to the screen based on the value of this argument.interactive-- whethermanage.pyis running in "interactive" mode; this is a boolean and so is eitherTrueorFalse. IfinteractiveisTrue, it's safe to prompt the user to input things on the command line (for example, the auth app only prompts to create a superuser wheninteractiveisTrue); ifinteractiveisFalse, functions which listen for this signal should not try to prompt for anything.
django.core.signals defines the following signals:
request_started
This signal is sent whenever Django begins processing an incoming HTTP request.
This signal doesn't provide any arguments.
request_finished
This signal is sent whenever Django finishes processing an incoming HTTP request.
This signal doesn't provide any arguments.
got_request_exception
This signal is sent whenever Django encounters an exception while processing an incoming HTTP request.
This signal doesn't provide any arguments.
django.test.signals defines the following signals:
template_rendered
This signal is sent by Django's testing framework whenever the test system renders a template; it's used by the test system to verify that the template rendered as expected. This signal is not emitted during normal operation of a Django server -- it is only available during testing.
Arguments sent with this signal:
sender-- theTemplateobject which was rendered.template-- same assender.context-- theContextwith which the template was rendered.
Other documentation
- Django signals -- blog entry by Ian Holsman which discusses signals in general.
- Initializing application data in Django -- blog entry by Alan Green which discusses use of the
post_syncdbsignal to provide initial application data. - Django tips: laying out an application -- blog entry by James Bennett which mentions the use of the
post_syncdbsignal to execute custom functions when an application is installed. - Django signals -- Mercurytide whitepaper explaining Django's dispatcher.