教你如何在Django 1.6中正确使用 Signal
简单回答是: 在其他方法无法使用的情况下, 才最后考虑使用signal.
因为新的django开发人员得知signal之后, 往往会很高兴去使用它. 他们在能使用signal的地方就使用signal, 并且这是他们觉得自己是django专家一样. 然而, 像这样编码一段时间后, django项目就会变得异常复杂, 许多内容都纠结在一起无法解开.
许多开发者也会将django signal和异步消息列队(例如celery)搞混. signal是同步处理, 因此通过signal调用大处理量的进程时并无法提高性能. 事实上, 将这些需要大处理量的进程移到signal中被视作是一种不好的习惯.
1. 何时使用signal
以下情况不要使用signal:
signal与一个model紧密相关, 并能移到该model的save()时
signal能使用model manager代替时
signal与一个view紧密相关, 并能移到该view中时
以下情况可以使用signal:
signal的receiver需要同时修改对多个model时
将多个app的相同signal引到同一receiver中处理时
在某一model保存之后将cache清除时
无法使用其他方法, 但需要一个被调函数来处理某些问题时
2. Signal的代替方法
使用mod而来manager
以下代码演示了当用户创建Event model时, 需要通知管理员, 如果改写model中的post_save(), 则需要添加额外的逻辑来区分用户还是管理员:
# myapp/managers.py from django.db import models class EventManager(models.Manager): def create_event(self, title, start, end, creator): event = self.model(title=title, start=start, end=end, creator=creator) event.save() event.notify_admins() return event
在model中设置model manager:
# myapp/models.py from django.conf import settings from django.core.mail import mail_admins from django.db import models from model_utils.models import TimeStampedModel from .managers import EventManager class Event(TimeStampedModel): STATUS_UNREVIEWED, STATUS_REVIEWED = (0, 1) STATUS_CHOICES = ( (STATUS_UNREVIEWED, "Unreviewed"), (STATUS_REVIEWED, "Reviewed") ) title = models.CharField(max_length=100) start = models.DateTimeField() end = model.dateTimeField() status = models.IntegerField(choices=STATUS_CHOICES, default=STATUS_UNREVIEWED) creator = models.ForeignField(settings.AUTH_USER_MODEL) objects = EventManager() def notify_admins(self): subject = "{user} submitted a new event!".format(user=self.creator.get_full_name()) message = """TITLE: {title} START: {start} END: {end}""".format(title=self.title, start=self.start, end=self.end) mail_admins(subject=subject, message=message, fail_silently=False)
在view中使用create_event()代替create()时, 便会通知管理员了.
在其他代码中验证model
如果你使用pre_save signal来验证某一model, 则应当尝试自己写一个validator取代之. 如果验证是通过ModelForm时, 通过改写clean()实现验证.
使用model的save()和delete()
如果使用pre_save 或 post_save signal, 如果可以, 则将这些代码移到model的save()方法中.
同样如果使用pre_delete 或 post_delete signal, 如果可以, 则将这些代码移到model的delte()方法中.
使用其他代码代替signal
如果可能, 我们可以将signal的逻辑使用其他帮助程序实现.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Steps to check the Django version: 1. Open a terminal or command prompt window; 2. Make sure Django has been installed. If Django is not installed, you can use the package management tool to install it and enter the pip install django command; 3. After the installation is complete , you can use python -m django --version to check the Django version.

Django and Flask are both leaders in Python Web frameworks, and they both have their own advantages and applicable scenarios. This article will conduct a comparative analysis of these two frameworks and provide specific code examples. Development Introduction Django is a full-featured Web framework, its main purpose is to quickly develop complex Web applications. Django provides many built-in functions, such as ORM (Object Relational Mapping), forms, authentication, management backend, etc. These features allow Django to handle large

Django is a complete development framework that covers all aspects of the web development life cycle. Currently, this framework is one of the most popular web frameworks worldwide. If you plan to use Django to build your own web applications, then you need to understand the advantages and disadvantages of the Django framework. Here's everything you need to know, including specific code examples. Django advantages: 1. Rapid development-Djang can quickly develop web applications. It provides a rich library and internal

How to check the django version: 1. To check through the command line, enter the "python -m django --version" command in the terminal or command line window; 2. To check in the Python interactive environment, enter "import django print(django. get_version())" code; 3. Check the settings file of the Django project and find a list named INSTALLED_APPS, which contains installed application information.

The differences are: 1. Django 1.x series: This is an early version of Django, including versions 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8 and 1.9. These versions mainly provide basic web development functions; 2. Django 2.x series: This is the mid-term version of Django, including 2.0, 2.1, 2.2 and other versions; 3. Django 3.x series: This is the latest version series of Django. Including versions 3.0, 3, etc.

How to upgrade Django version: steps and considerations, specific code examples required Introduction: Django is a powerful Python Web framework that is continuously updated and upgraded to provide better performance and more features. However, for developers using older versions of Django, upgrading Django may face some challenges. This article will introduce the steps and precautions on how to upgrade the Django version, and provide specific code examples. 1. Back up project files before upgrading Djan

django is the backend. Details: Although Django is primarily a backend framework, it is closely related to front-end development. Through features such as Django's template engine, static file management, and RESTful API, front-end developers can collaborate with back-end developers to build powerful, scalable web applications.

Django, Flask, and FastAPI: Which framework is right for beginners? Introduction: In the field of web application development, there are many excellent Python frameworks to choose from. This article will focus on the three most popular frameworks, Django, Flask and FastAPI. We will evaluate their features and discuss which framework is best for beginners to use. At the same time, we will also provide some specific code examples to help beginners better understand these frameworks. 1. Django: Django
