django 訊號

Bobbyby發表於2018-07-10

django存在一個’訊號排程程式’, 可以實現當某事件在框架內發生時,通知到我們的應用程式。比如當某個時間(event)發生時允許若干寄件人(sender)通知一組接受者(receivers)

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.

具體比如, 當某個使用者被建立後, 會通知某個程式, 建立一個token, 類似於mysql觸發器.

Model signals可以分為一下幾種:

pre_init 某個例項馬上要初始化了
post_init 某個例項已經初始化了
pre_save 個例項即將要儲存入庫了
post_save 某個例項即已經儲存入庫了
pre_delete 某個例項即將要刪除了
post_delete 某個例項即已經刪除了
class_prepared 某個class準備好了
m2m_changed 模型的ManyToManyField改變時觸發

使用:

場景1: 建立使用者後加密密碼(因某種原因存入資料庫的是明文)
  1. 在apps/user下新建signals.py
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.dispatch import receiver
User = get_user_model()

@receiver(post_save, sender=User)
def create_user(sender, instance=None, created=False, **kwargs):
    if created:
        password = instance.password
        instance.set_password(password)
        instance.save()     

signal接受函式需要確保將此程式碼段放置在已安裝的models.py模組或Django在啟動時匯入的其他位置

  1. 載入signals設定: apps/users/init.py中填寫:
default_app_config = 'users.apps.UsersConfig'

  1. 隨後在apps/user/app.py的config類下重寫ready方法:
from django.apps import AppConfig
class UsersConfig(AppConfig):
    pass
    def ready(self):
        import users.signals        

場景2: 生成token

如果你希望每個使用者擁有自動生成的令牌,你可以簡單地捕獲使用者的post_save訊號。

原文: jango-REST-framework-documentation

from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

參考:

相關文章