Django Signals

2018-03-30  本文已影响0人  whenitsallover

official site:
https://docs.djangoproject.com/en/2.0/topics/signals/

Django includes a “signal dispatcher” which helps allow decoupled applications get notified when actions occur elsewhere in the framework. In a nutshell, signals allow certain senders to notify a set of receivers that some action has taken place. They’re especially useful when many pieces of code may be interested in the same events.

Listening to signals

To receive a signal, register a receiver function using the Signal.connect() method. The receiver function is called when the signal is sent.

| Parameters: |

Let’s see how this works by registering a signal that gets called after each HTTP request is finished. We’ll be connecting to therequest_finished signal.

Receiver functions

First, we need to define a receiver function. A receiver can be any Python function or method:

def my_callback(sender, **kwargs):
    print("Request finished!")

Notice that the function takes a sender argument, along with wildcard keyword arguments (**kwargs); all signal handlers must take these arguments.

Connecting receiver functions

receiver`(signal)[source]

Parameters: signal – A signal or a list of signals to connect a function to.
Here’s how you connect with the decorator:

from django.core.signals import request_finished
from django.dispatch import receiver

@receiver(request_finished)
def my_callback(sender, **kwargs):
    print("Request finished!")

Now, our my_callback function will be called each time a request finishes.

Where should this code live?

Strictly speaking, signal handling and registration code can live anywhere you like, although it’s recommended to avoid the application’s root module and its models module to minimize side-effects of importing code.

In practice, signal handlers are usually defined in a signals submodule of the application they relate to. Signal receivers are connected in the ready() method of your application configuration class. If you’re using the receiver() decorator, simply import the signals submodule inside ready().

An example of Signal applied in Django

Consider, for example, you may want to record the count every time a user is created in the UserInfo, Here is how it works:

models.py

from django.db import models
from django.dispatch import receiver
from django.db.models.signals import Signal,post_save
from django.db.models import F


class UserInfo(models.Model):
    name = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
    roles = models.ManyToManyField(to='Role')
    depart = models.ForeignKey('Department')

    def __str__(self):
        return self.name

class Counter(models.Model):
    count = models.IntegerField(default=0)

@receiver(post_save,sender=UserInfo) # receiver decorator
def auto_plus(sender,**kwargs):
    if kwargs.get('created',False):
        counter = Counter.objects.get(id=1)
        counter.count = F('count') + 1
        counter.save()



post_save.connect(auto_plus,sender=UserInfo)  post_save()method 

class Role(models.Model):
    title = models.CharField(max_length=32)

    def __str__(self):
        return self.title


class Department(models.Model):
    dep = models.CharField(max_length=32)

    def __str__(self):
        return self.dep

views.py


class UserInfoForm(forms.ModelForm):

    class Meta:
        model = models.UserInfo
        fields = '__all__'


def user(request):
    if request.method == 'GET':
        form = UserInfoForm()
        return render(request,'index.html',{'form':form})
    form = UserInfoForm(data=request.POST)
    if form.is_valid():
        form.save()
        return HttpResponse('添加成功')
    return render(request,'index.html',{'form':form})

def index(request):

    return render(request,'index.html')

上一篇 下一篇

猜你喜欢

热点阅读