The signal in Django

Source: Internet
Author: User

Signal

Django provides a "signal dispatcher" that allows decoupled applications to be notified when operations occur elsewhere in the framework. Simply put, a signal allows a specific sender to notify a group of receiver that certain operations have occurred. This is useful in situations where multiple code is associated with the same event.

Built-in signal model signal

The Django.db.models.signals module defines a set of signals sent by the model system.

Pre_init

Django.db.models.signals.pre_init
Each time you instantiate a Django model, the signal is sent at the beginning of the model's __init__ () method.

Parameters with this signal:

Sender
A model class that has just created an instance.
ARGS
The list of positional parameters passed to __init__ ():
Kwargs
Dictionary of keyword arguments passed to __init__ ():

For example:

 from Import  = models. Publisher (name=' Shahe press ')

The parameters sent to the Pre_init handler will be:

Parameters value
s Ender Publisher (class itself)
args < Span class= "Pre" >[] (an empty list because no positional parameters are passed to __init__ () . )
Kwargs {' name ': "Shahe Publishing house " Span id= "yiyi-50" class= "Pre yiyi-st" >

Pre_save

Django.db.models.signals.pre_save
This is sent at the beginning of the model's Save () method.

Parameters with this signal:

Sender
Model class.
Instance
The actual instance being saved.
Raw
A Boolean value of TRUE if the model is saved as shown (that is, when the retention device is loaded). Other records in the database should not be queried/modified because the database may not be in a consistent state.
Using
The database alias being used.
Update_fields
If a field is passed to the Model.save () method then it is the set of fields passed, otherwise none.

Post_save

Django.db.models.signals.post_save
Like Pre_save, but sent at the end of the Save () method.

Parameters with this signal:

Sender
Model class.
Instance
The actual instance being saved.
Created
A Boolean value of True if a new record is created.
Raw
A Boolean value of TRUE if the model is saved as shown (that is, when the retention device is loaded). Other records in the database should not be queried/modified because the database may not be in a consistent state.
Using
The database alias being used.
Update_fields
If a field is passed to the Model.save () method then it is the set of fields passed, otherwise none.

Pre_delete

Django.db.models.signals.pre_delete
Sent at the beginning of the Delete () method of the model and the queryset of the Delete () method.

Parameters with this signal:

Sender
Model class.
Instance
The actual instance being deleted.
Using
The database alias being used.

Post_delete

Django.db.models.signals.post_delete
Like Pre_delete, but sent at the end of the delete () method of the model and the queryset of the Delete () method.

Parameters with this signal:

Sender
Model class.
Instance
The actual instance being deleted.

Note that the object will no longer be in the database, so use this instance with great care.

Using
The database alias being used.

M2m_changed

Django.db.models.signals.m2m_changed
Sent when Manytomanyfield is changed on a model instance. Strictly speaking, this is not a model signal because it is sent by Manytomanyfield, but because it complements Pre_save/post_save and PRE_DELETE/POST_DELETE when tracking model changes, it is included here.

Parameters with this signal:

Sender
Describes the intermediate model class for Manytomanyfield. This class is automatically created when you define many-to-many fields, and you can use the through property on many-to-many fields to access it.
Instance
An instance of a many-to-many relationship update. This can be an instance of the sender or Manytomanyfield related class.
Action
A string that indicates the type of update completed on the relationship. This can be one of the following:

"Pre_add"
Before sending one or more objects is added to the relationship.
"Post_add"
After the sending of one or more objects is added to the relationship.
"Pre_remove"
Before sending one or more objects to be removed from the relationship.
"Post_remove"
After a send one or more objects are removed from the relationship.
"Pre_clear"
Before the send relationship is cleared.
"Post_clear"
The send relationship is then cleared.
Reverse
Indicates which side of the relationship is updated (that is, if it is a forward or reverse relationship that is being modified).
Model
A class that is added to an object that is removed from the relationship or purged from the relationship.
Pk_set
For Pre_add,post_add,pre_remove and Post_remove operations, this is a set of primary key values to join or remove from the relationship.

For Pre_clear and post_clear operations, this is none.

Using
The database alias being used.

Class_prepared

Django.db.models.signals.class_prepared
Whenever the model class is "ready" to send-that is, once the model has been defined and registered in the Django model system. This signal is used internally by Django, and it is typically not used for third-party applications.

Because this signal is sent during the application registry cluster process and runs Appconfig.ready () after the registry is fully populated, the method cannot be used to connect to the sink. One possibility is to connect them appconfig.__init__ (), taking care not to import the model or trigger a call to the application registry.

Parameters to be sent using this signal:

Sender
Ready's model class.

Management Signal Pre_migrate

Django.db.models.signals.pre_migrate
Sent by the migrate command before you begin installing the application. For applications that are missing the models module, they are not sent.

Parameters with this signal:

Sender
The AppConfig instance that the application is about to migrate/synchronize.
App_config
Same as sender.
Verbosity
Indicates how much information manage.py prints on the screen. For more information, see the--verbosity flag.

The function that listens to pre_migrate should adjust the output to the screen according to the value of this parameter.

Interactive
If Interactive is true, it is safe to prompt the user to enter content on the command line. If interactive is false, the ability to listen for this signal should not attempt to prompt anything.

For example, when Interactive is true, the Django.contrib.auth application only prompts you to create a superuser.

Using
The alias of the database on which the command will run.
Plan
New features in Django 1.10.
The migration plan will be used for the migration run. Although the plan is not a public API, this requires knowing the plan in rare cases. A schedule is a list of two tuples, the first of which is an instance of the migration class, and the second item shows whether the migration is rolled back (True) or applied (False

Apps
New features in Django 1.10.
An instance of an application that contains the state of the project before the migration is run. It should be used instead of the global apps registry to retrieve the model to perform the operation.

Post_migrate

Django.db.models.signals.post_migrate
Sent at the end of the migrate (even if not migrated) and flush commands. For applications that are missing the models module, they are not sent.

The handler for this signal must not perform a database schema change, because running during the migrate command may cause the flush command to fail.

Parameters with this signal:

Sender
The AppConfig instance of the application that was just installed.
App_config
Same as sender.
Verbosity
Indicates how much information manage.py prints on the screen. For more information, see the--verbosity flag.

The function that listens to post_migrate should adjust the output to the screen according to the value of this parameter.

Interactive
If Interactive is true, it is safe to prompt the user to enter content on the command line. If interactive is false, the ability to listen for this signal should not attempt to prompt anything.

For example, when Interactive is true, the Django.contrib.auth application only prompts you to create a superuser.

Using
The database alias used for synchronization. Defaults to the default database.
Plan
New features in Django 1.10.
Migration plan for the migration run. Although the plan is not a public API, this requires knowing the plan in rare cases. A schedule is a list of two tuples, the first of which is an instance of the migration class, and the second item shows whether the migration is rolled back (True) or applied (False

Apps
New features in Django 1.10.
Contains an instance of an application that migrates the state of a post-run project. It should be used instead of the global apps registry to retrieve the model to perform the operation.

Request/Response Signal

The signal sent by the core framework when processing the request.

request_started

Django.core.signals. request_started
Sent when Django starts processing an HTTP request.

Parameters with this signal:

Sender
The handler class-for example, Django.core.handlers.wsgi.WsgiHandler-processes the request.
ENVIRON
The Environ dictionary is provided to the request.

Request_finished

Django.core.signals.request_finished
Sent when Django finishes passing an HTTP response to the client.

Parameters with this signal:

Sender
Handler class, as above.

Got_request_exception

Django.core.signals. got_request_exception
This signal is sent when Django encounters an exception while processing an incoming HTTP request.

Parameters with this signal:

Sender
Handler class, as above.
Request
The HttpRequest object.

Test signal

The signal is only sent when the running tests.

Setting_changed

Django.test.signals.setting_changed
When using the Django.test.TestCase.settings () context Manager or django.test.override_settings () Adorner/context Manager

Actually sent two times: when the new value ("Setup") is applied and the original value is restored ("removed"). Use the Enter parameter to differentiate between the two.

You can also import this signal from django.core.signals to avoid importing from django.test in non-test cases.

Parameters with this signal:

Sender
Sets a handler.
Setting
The name of the setting.
Value
The setting value after the change. For a setting that does not exist initially, value is none during the disassembly phase.
Enter
A Boolean value of true if the setting is applied, false if restored.

Template_rendered

Django.test.signals.template_rendered
Sent when the test system renders the template. This signal is not emitted during normal operation of the Django server-it is only available during testing.

Parameters with this signal:

Sender
The template object being rendered.
Template
Same as the sender.
Context
The context in which the template renders.

Database Wrapper

The signal sent by the database wrapper when the database connection is started.

connection_created

django.db.backends.signals.connection_created
Sent when the database wrapper is initially connected to the database. This is especially useful if you want to send any subsequent connection commands to the SQL backend.

Parameters with this signal:

Sender
Database wrapper classes-that is, django.db.backends.postgresql.DatabaseWrapper or django.db.backends.mysql.DatabaseWrapper, etc.
Connection
Open the database connection. This can be used in multiple database configurations to differentiate connection signals from different databases.

Using signals

Go back to the front face. How do I perform a specified operation in Django every time the ORM is saved to the database?

Receiver function

Receiver can be any Python function or method:

def my_callback (sender, * *Kwargs)    :print(sender    )print( Kwargs)    print(" to save the AH!"  ")    print('-' * 120)
Monitoring signal

Once a specified signal is triggered, the receiver function I specified is executed.

Our current requirement is that the model layer does what it does when it executes the saved action.

So it's supposed to execute my_callback once the pre_save signal is triggered, and for the built-in signal the Django framework automatically triggers the trigger, and we just have to tell it what to do after the signal is triggered:

Pre_save.connect (My_callback)

Next, as long as the Save () operation involving the ORMC Eng Polygon is involved, the My_callback function I defined is automatically executed.

For example:

A3 = Author.objects.create (name=' test signal-author '= Book.objects.create (title=')  Test Signal-book ')

Output:

<class 'App02.models.Author'>{'Signal': <django.db.models.signals.modelsignal object at 0x108e0d198>'instance': <author: Test Signal-author;'Raw': False,'using':'default','Update_fields': None} to save Ah! --------------------------------------------------------------------------------------------------------------- ---------(0.001) SELECT @ @SQL_AUTO_IS_NULL; args=None (0.001) INSERT into ' app02_author ' (' name ') VALUES ('Test Signal-author'); args=['Test Signal-author']<class 'App02.models.Book'>{'Signal': <django.db.models.signals.modelsignal object at 0x108e0d198>'instance': <book: Test Signal-book;'Raw': False,'using':'default','Update_fields': None} to save Ah! --------------------------------------------------------------------------------------------------------------- ---------(0.001) INSERT into ' App02_book ' (' title ') VALUES ('Test Signal-book'); args=['Test Signal-book']
Using adorners to listen for signals
#using Adorner mode fromDjango.db.models.signalsImportPre_save fromDjango.dispatchImportreceiver@receiver (Pre_save)defMy_callback (Sender, * *Kwargs):Print(Sender)Print(Kwargs)Print("to save it! ")    Print('-'* 120)
Custom Signal

All listed above are the signals built into the Django framework, and of course we can customize the signal.

Defining the Signal

All signals are examples of django.dispatch.Signal. Providing_args is a list of parameter names that the signal will provide to listeners. This is theoretically true, but there is actually no check to ensure that these parameters are provided to listeners.

As an example:

# Custom Signal  from Import  = Signal (providing_args=['amount'temperature' ])

This defines a signal that the bath water has been burnt, and it accepts two parameters: Amount represents the amount of water, and temperature represents the temperature.

Register receiver
 from Import receiver@receiver (Bath_done) def my_action (sender, * *Kwargs)    :print(sender    )print( Kwargs)    print(' take off your clothes and soak in a bath!  ')
Trigger Signal

Scarlett cooked a bathtub 40 degrees of bath water, durant to open drink.

Bath_done.send (sender=' Scarlett ', amount=' a bathtub ', temperature= ' 40° ')

The signal in Django

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.