from django.dispatch import Signal user_email_changed = Signal(providing_args=['user', 'new_email', 'old_email'])
import os import time import threading import warnings from django.conf import settings from django.db import connections, router from django.db.utils import ConnectionRouter from django.dispatch import receiver, Signal from django.utils import timezone from django.utils.functional import empty template_rendered = Signal(providing_args=["template", "context"]) setting_changed = Signal(providing_args=["setting", "value", "enter"]) # Most setting_changed receivers are supposed to be added below, # except for cases where the receiver is related to a contrib app. # Settings that may not work well when using 'override_settings' (#19031) COMPLEX_OVERRIDE_SETTINGS = {'DATABASES'} @receiver(setting_changed) def clear_cache_handlers(**kwargs): if kwargs['setting'] == 'CACHES': from django.core.cache import caches caches._caches = threading.local() @receiver(setting_changed)
from django.dispatch import Signal product_viewed_signal = Signal(providing_args=['instance', 'request'])
class FoiAttachment(models.Model): belongs_to = models.ForeignKey(FoiMessage, null=True, verbose_name=_("Belongs to message"), on_delete=models.CASCADE, related_name='foiattachment_set') name = models.CharField(_("Name"), max_length=255) file = models.FileField(_("File"), upload_to=upload_to, max_length=255, storage=HashedFilenameStorage(), db_index=True) size = models.IntegerField(_("Size"), blank=True, null=True) filetype = models.CharField(_("File type"), blank=True, max_length=100) format = models.CharField(_("Format"), blank=True, max_length=100) can_approve = models.BooleanField(_("User can approve"), default=True) approved = models.BooleanField(_("Approved"), default=False) redacted = models.ForeignKey('self', verbose_name=_("Redacted Version"), null=True, blank=True, on_delete=models.SET_NULL, related_name='unredacted_set') is_redacted = models.BooleanField(_("Is redacted"), default=False) converted = models.ForeignKey('self', verbose_name=_("Converted Version"), null=True, blank=True, on_delete=models.SET_NULL, related_name='original_set') is_converted = models.BooleanField(_("Is converted"), default=False) timestamp = models.DateTimeField(null=True, default=timezone.now) pending = models.BooleanField(default=False) document = models.OneToOneField(Document, null=True, blank=True, related_name='attachment', on_delete=models.SET_NULL) objects = FoiAttachmentManager() attachment_published = Signal(providing_args=[]) class Meta: ordering = ('name', ) unique_together = (("belongs_to", "name"), ) # order_with_respect_to = 'belongs_to' verbose_name = _('Attachment') verbose_name_plural = _('Attachments') def __str__(self): return "%s (%s) of %s" % (self.name, self.size, self.belongs_to) def index_content(self): return "\n".join((self.name, )) def get_html_id(self): return _("attachment-%(id)d") % {"id": self.id} def get_bytes(self): self.file.open(mode='rb') try: return self.file.read() finally: self.file.close() @property def can_redact(self): return self.redacted is not None or (self.can_approve and self.is_pdf) @property def can_delete(self): if not self.belongs_to.is_postal: return False if not self.can_approve: return False now = timezone.now() return self.timestamp > (now - DELETE_TIMEFRAME) @property def can_edit(self): return self.can_redact or self.can_delete or self.can_approve @property def allow_link(self): return self.approved or not (self.can_redact and self.can_approve) @property def is_pdf(self): return self.filetype in PDF_FILETYPES or ( self.name and self.name.endswith('.pdf') and self.filetype == 'application/octet-stream') @property def is_image(self): return (self.filetype.startswith('image/') or self.filetype in IMAGE_FILETYPES or self.name.endswith( ('.jpg', '.jpeg', '.gif', '.png'))) @property def is_mail_decoration(self): return self.is_image and self.size and self.size < 1024 * 60 @property def is_irrelevant(self): return self.is_mail_decoration or self.is_signature @property def is_signature(self): return self.name.endswith( ('.p7s', '.vcf', '.asc')) and self.size < 1024 * 15 @property def can_embed(self): return self.filetype in EMBEDDABLE_FILETYPES or self.is_pdf def get_anchor_url(self): if self.belongs_to: return self.belongs_to.get_absolute_url() return '#' + self.get_html_id() def get_domain_anchor_url(self): return '%s%s' % (settings.SITE_URL, self.get_anchor_url()) def get_absolute_url(self): fr = self.belongs_to.request return reverse('foirequest-show_attachment', kwargs={ 'slug': fr.slug, 'message_id': self.belongs_to.pk, 'attachment_name': self.name }) def get_file_url(self): ''' Hook method for django-filingcabinet ''' return self.get_absolute_domain_file_url() def get_file_path(self): return self.file.path def get_crossdomain_auth(self): from ..auth import AttachmentCrossDomainMediaAuth return AttachmentCrossDomainMediaAuth({ 'object': self, }) def send_internal_file(self): return self.get_crossdomain_auth().send_internal_file() def get_absolute_domain_url(self): return '%s%s' % (settings.SITE_URL, self.get_absolute_url()) def get_absolute_domain_auth_url(self): return self.get_crossdomain_auth().get_full_auth_url() def get_authorized_absolute_domain_file_url(self): return self.get_absolute_domain_file_url(authorized=True) def get_absolute_domain_file_url(self, authorized=False): return self.get_crossdomain_auth().get_full_media_url( authorized=authorized) def approve_and_save(self): self.approved = True self.save() if self.document: foirequest = self.belongs_to.request should_be_public = foirequest.public if self.document.public != should_be_public: self.document.public = should_be_public self.document.save() self.attachment_published.send(sender=self) def remove_file_and_delete(self): if self.file: other_references = FoiAttachment.objects.filter( file=self.file.name).exclude(id=self.id).exists() if not other_references: self.file.delete(save=False) self.delete() def can_convert_to_pdf(self): ft = self.filetype.lower() name = self.name.lower() return (self.converted_id is None and can_convert_to_pdf(ft, name=name)) def create_document(self, title=None): if self.document is not None: return self.document if not self.is_pdf: return if self.converted_id or self.redacted_id: return foirequest = self.belongs_to.request doc = Document.objects.create( original=self, user=foirequest.user, public=foirequest.public, title=title or self.name, foirequest=self.belongs_to.request, publicbody=self.belongs_to.sender_public_body) self.document = doc self.save() return doc
navigation. You will get the request as a keyword argument ``request``. Receivers are expected to return a list of dictionaries. The dictionaries should contain at least the keys ``label`` and ``url``. You can also return a fontawesome icon name with the key ``icon``, it will be respected depending on the type of navigation. You should also return an ``active`` key with a boolean set to ``True``, when this item should be marked as active. The ``request`` object will have an attribute ``event``. If you use this, you should read the documentation on :ref:`how to deal with URLs <urlconf>` in pretix. As with all plugin signals, the ``sender`` keyword argument will contain the event. """ nav_topbar = Signal( providing_args=["request"] ) """ This signal allows you to add additional views to the top navigation bar. You will get the request as a keyword argument ``request``. Receivers are expected to return a list of dictionaries. The dictionaries should contain at least the keys ``label`` and ``url``. You can also return a fontawesome icon name with the key ``icon``, it will be respected depending on the type of navigation. If set, on desktops only the ``icon`` will be shown. The ``title`` property can be used to set the alternative text. If you use this, you should read the documentation on :ref:`how to deal with URLs <urlconf>` in pretix. This is no ``EventPluginSignal``, so you do not get the event in the ``sender`` argument and you may get the signal regardless of whether your plugin is active.
'page': page, 'results_var': results_var, 'counter': counter, 'query': query, 'title': _(u'FileBrowser'), 'settings_var': get_settings_var(), 'breadcrumbs': get_breadcrumbs(query, path), 'breadcrumbs_title': "" }, context_instance=Context(request)) browse = staff_member_required(never_cache(browse)) # mkdir signals filebrowser_pre_createdir = Signal(providing_args=["path", "dirname"]) filebrowser_post_createdir = Signal(providing_args=["path", "dirname"]) def mkdir(request): """ Make Directory. """ from djlime_filebrowser.forms import MakeDirForm # QUERY / PATH CHECK query = request.GET path = get_path(query.get('dir', '')) if path is None: msg = _('The requested Folder does not exist.')
# jobs_board_main/signals.py from django.dispatch import Signal new_subscriber = Signal(providing_args=["job", "subscriber"])
from django.dispatch import Signal # providing_args=['request', 'refresh_token'] refresh_token_revoked = Signal() # providing_args=['request', 'refresh_token', 'refresh_token_issued'] refresh_token_rotated = Signal()
from django.dispatch import Signal aspect_class_prepared = Signal(providing_args=["class"]) data_pre_save = Signal(providing_args=["instance"]) data_post_save = Signal(providing_args=["instance"]) data_pre_delete = Signal(providing_args=["instance"]) data_post_delete = Signal(providing_args=["instance"]) class_prepared = Signal(providing_args=["instance"])
# -*- coding: utf-8 -*- from django.dispatch import Signal change_source = Signal()
from django.dispatch import Signal # We want to signal when an invoice was created and is ready to be looked at. # (we cannot use the built-in post_save signal for that because just after an # invoice is saved it doesn't yet have charges attached) invoice_ready = Signal(use_caching=True) credit_card_registered = Signal() credit_card_deleted = Signal() debt_paid = Signal() new_delinquent_account = Signal() new_compliant_account = Signal()
# Prototype from . import models from django.dispatch import receiver from django.dispatch import Signal new_message = Signal(providing_args=['instance']) # it will be used in views [on sending message] to send notification signal # call it as new_message.send(sender=Message, instance = msg_instance) # Requires connection # receiver function will look like @receiver(new_message, sender=models.Message) def create_notification(sender, **kwargs): msg_instance = kwargs.get('instance', None) if msg_instance: models.Notification.objects.create( receiver=msg_instance.receiver, header='New Message!', body= f'Dear {msg_instance.receiver} You have received a message from {msg_instance.sender}' )
from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.dispatch import receiver, Signal # from django_rest_passwordreset.signals import reset_password_token_created from rest_framework.authtoken.models import Token new_user_registered = Signal(providing_args=['user_id'], ) @receiver(new_user_registered) def get_token(user_id=None, **kwargs): token = Token.objects.create(user=user_id) message = EmailMultiAlternatives( # title: f"Password Reset Token for {token.user.email}", # message: token.key, # from: settings.DEFAULT_FROM_EMAIL, # to: [token.user.email]) message.send()
from dimagi.ext.jsonobject import JsonObject from django.db.models.signals import post_save from django.db import models from django.conf import settings from django.contrib.auth.models import User from django.forms import model_to_dict try: from dimagi.utils.threadlocals import get_current_user except: from auditcare.utils import get_current_user from django.dispatch import Signal log = logging.getLogger(__name__) user_login_failed = Signal(providing_args=['request', 'username']) def model_to_json(instance): """ converts a django model into json in the format used by jsonobject """ class DummyObject(JsonObject): pass json_model = model_to_dict(instance) for key, value in json_model.items(): if isinstance(value, QuerySet): json_model[key] = list(value)
class Registry(defaultdict): """ Registry of side effect functions. This class is a defaultdict(list) that contains a mapping of the side-effect label to the functions that should run after the function has completed. It has two additional methods - `add`, which is used to register a new function against a label, and `contains` which is used to look up a function against a label. """ # if using the disable_side_effects context manager or decorator, # then this signal is used to communicate details of events that # would have fired, but have been suppressed. # RemovedInDjango40Warning: providing_args=["label"] suppressed_side_effect = Signal() def __init__(self) -> None: self._lock = threading.Lock() self._suppress = False super(Registry, self).__init__(list) def by_label(self, value: str) -> RegistryType: """Filter registry by label (exact match).""" return {k: v for k, v in self.items() if k == value} def by_label_contains(self, value: str) -> RegistryType: """Filter registry by label (contains string).""" return {k: v for k, v in self.items() if value in k} def contains(self, label: str, func: Callable) -> bool: """ Lookup label: function mapping in the registry. The fname of the function is used in the lookup, as running a simple `func in list` check doesn't work. """ return fname(func) in [fname(f) for f in self[label]] def add(self, label: str, func: Callable) -> None: """ Add a function to the registry. Args: label: string, the name of the side-effect - this is used to bind two function - the function that @has_side_effects and the function that @is_side_effect. func: a function that will be called when the side-effects are executed - this will be passed all of the args and kwargs of the original function. """ with self._lock: self[label].append(func) def _run_side_effects(self, label: str, *args: Any, return_value: Any | None = None, **kwargs: Any) -> None: if settings.TEST_MODE_FAIL: raise SideEffectsTestFailure(label) for func in self[label]: _run_func(func, *args, return_value=return_value, **kwargs) def run_side_effects(self, label: str, *args: Any, return_value: Any | None = None, **kwargs: Any) -> None: """ Run registered side-effects functions, or suppress as appropriate. If TEST_MODE is on, or the _suppress attr is True, then the side-effects are not run, but the `suppressed_side_effect` signal is sent - this is primarily used by the disable_side_effects context manager to register which side-effects events were suppressed (for testing purposes). NB even if the side-effects themselves are not run, this method will try to bind all of the receiver functions - this is to ensure that incompatible functions fail hard and early. """ # TODO: this is all becoming over-complex - need to simplify this self.try_bind_all(label, *args, return_value=return_value, **kwargs) if self._suppress or settings.TEST_MODE: self.suppressed_side_effect.send(Registry, label=label) else: self._run_side_effects(label, *args, return_value=return_value, **kwargs) def try_bind_all(self, label: str, *args: Any, return_value: Any | None = None, **kwargs: Any) -> None: """ Test all receivers for signature compatibility. Raise SignatureMismatch if any function does not match. """ for func in self[label]: if not (try_bind(func, *args, return_value=return_value, **kwargs) or try_bind(func, *args, **kwargs)): raise SignatureMismatch(func)
# # A copy of this license - GNU General Public License - is available # at the root of the source code of this program. If not, # see http://www.gnu.org/licenses/. # ############################################################################## from django.contrib.auth.models import Group from django.db.models.signals import post_save, post_delete from django.dispatch import receiver, Signal from base import models as mdl from osis_common.models.serializable_model import SerializableModel from django.contrib.auth.models import Permission from osis_common.models.signals.authentication import user_created_signal, user_updated_signal from django.conf import settings person_created = Signal(providing_args=['person']) @receiver(user_created_signal) @receiver(user_updated_signal) def update_person(sender, **kwargs): user = kwargs.get('user') user_infos = kwargs.get('user_infos') person = mdl.person.find_by_global_id(user_infos.get('USER_FGS')) person = _create_update_person(user, person, user_infos) _add_person_to_group(person) return person def _add_person_to_group(person): # Check tutor
# GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from django.apps import apps from django.db import models, connection from django.db.utils import DEFAULT_DB_ALIAS, ConnectionHandler from django.db.models.signals import pre_save, post_delete import logging logger = logging.getLogger(__name__) from django.dispatch import Signal cleanup_pre_delete = Signal(providing_args=["file"]) cleanup_post_delete = Signal(providing_args=["file"]) def _find_models_with_filefield(): result = [] for model in apps.get_models(): for field in model._meta.fields: if isinstance(field, models.FileField): result.append(model) break return result def _delete_file(file_obj): def delete_from_storage():
""" This module contains all general use signals. """ from django.dispatch import Signal # Signal that fires when a user is graded COURSE_GRADE_CHANGED = Signal( providing_args=["user", "course_grade", "course_key", "deadline"]) # Signal that fires when a user is awarded a certificate in a course (in the certificates django app) # TODO: runtime coupling between apps will be reduced if this event is changed to carry a username # rather than a User object; however, this will require changes to the milestones and badges APIs COURSE_CERT_AWARDED = Signal( providing_args=["user", "course_key", "mode", "status"]) # Signal that indicates that a user has passed a course. COURSE_GRADE_NOW_PASSED = Signal(providing_args=[ 'user', # user object 'course_id', # course.id ]) # Signal that indicates that a user has become verified LEARNER_NOW_VERIFIED = Signal(providing_args=['user'])
from django.dispatch import Signal from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from .settings import ( COUPON_TYPES, CODE_LENGTH, CODE_CHARS, SEGMENTED_CODES, SEGMENT_LENGTH, SEGMENT_SEPARATOR, ) user_model = get_user_model() redeem_done = Signal(providing_args=["coupon"]) class CouponManager(models.Manager): def create_coupon(self, type, value, users=[], valid_until=None, prefix="", campaign=None, user_limit=None): coupon = self.create( value=value, code=Coupon.generate_code(prefix), type=type, valid_until=valid_until, campaign=campaign, ) if user_limit is not None: # otherwise use default value of model coupon.user_limit = user_limit try: coupon.save()
from django.shortcuts import render, HttpResponse from django.core.signals import request_finished from django.dispatch import receiver, Signal from .models import post #this module is for timstamp request_counter_signal = Signal(providing_args=['timestamp']) def home(request): request_counter_signal.send(sender=post, timestamp='2019-10-10') return HttpResponse("Here's the Response") @receiver(request_finished) def post_request_reciver(sender, **kwargs): print("Request finished!") @receiver(request_counter_signal) def post_counter_signal_reciver(sender, **kwargs): print(kwargs)
class AdvUser(AbstractUser): is_activated = models.BooleanField(default=True, db_index=True, verbose_name='Прошел активацию?') send_messages = models.BooleanField( default=True, verbose_name='Слать оповещение о новых комментариях?') class Meta(AbstractUser.Meta): pass from django.dispatch import Signal from .utilites import send_activation_notification user_registrated = Signal(providing_args=['instance']) def user_registrated_dispatcher(sender, **kwargs): send_activation_notification(kwargs['instance']) user_registrated.connect(user_registrated_dispatcher) class Rubric(models.Model): name = models.CharField(max_length=20, db_index=True, unique=True, verbose_name='Название') order = models.SmallIntegerField(default=0,
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.dispatch import Signal __all__ = ["spike_analysis", "spike_validation_rd", "spike_validation_st"] __author__ = "pmeier82" spike_analysis = Signal() spike_validation_rd = Signal() spike_validation_st = Signal() if __name__ == "__main__": pass
from django.dispatch import Signal # instance: the User who follows # target_user: the User who is being followed follow_user_signal = Signal(providing_args=['instance', 'target_user']) # instance: the User who follows # target_user: the User who is being unfollowed unfollow_user_signal = Signal(providing_args=['instance', 'target_user'])
from django.dispatch import Signal object_viewed_signal = Signal(providing_args=["instance", "request"])
from django.conf import settings from django.contrib.auth import login, get_backends from django.dispatch import Signal # A new user has registered. user_registered = Signal(providing_args=["user", "request"]) # A user has activated his or her account. user_activated = Signal(providing_args=["user", "request"]) def login_user(sender, user, request, **kwargs): """ Automatically authenticate the user when activated """ backend = get_backends()[0] # Hack to bypass `authenticate()`. user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) login(request, user) request.session['REGISTRATION_AUTO_LOGIN'] = True request.session.modified = True if getattr(settings, 'REGISTRATION_AUTO_LOGIN', False): user_activated.connect(login_user)
log = logging.getLogger("edx.student") AUDIT_LOG = logging.getLogger("audit") # Used as the name of the user attribute for tracking affiliate registrations REGISTRATION_AFFILIATE_ID = 'registration_affiliate_id' REGISTRATION_UTM_PARAMETERS = { 'utm_source': 'registration_utm_source', 'utm_medium': 'registration_utm_medium', 'utm_campaign': 'registration_utm_campaign', 'utm_term': 'registration_utm_term', 'utm_content': 'registration_utm_content', } REGISTRATION_UTM_CREATED_AT = 'registration_utm_created_at' # used to announce a registration REGISTER_USER = Signal(providing_args=["user", "registration"]) # .. toggle_name: registration.enable_failure_logging # .. toggle_implementation: WaffleFlag # .. toggle_default: False # .. toggle_description: Enable verbose logging of registration failure messages # .. toggle_use_cases: temporary # .. toggle_creation_date: 2020-04-30 # .. toggle_target_removal_date: 2020-06-01 # .. toggle_warnings: This temporary feature toggle does not have a target removal date. REGISTRATION_FAILURE_LOGGING_FLAG = LegacyWaffleFlag( waffle_namespace=LegacyWaffleFlagNamespace(name='registration'), flag_name='enable_failure_logging', module_name=__name__, )
# nnmware(c)2012-2017 from __future__ import unicode_literals from django.dispatch import Signal action = Signal(providing_args=[ 'user', 'verb', 'action_object', 'target', 'description', 'timestamp' ]) # Signal for create new notice notice = Signal(providing_args=[ 'user', 'sender', 'verb', 'target', 'description', 'notice_type' ])
# -*- coding: utf-8 -*- from django.dispatch import Signal layer_created = Signal(providing_args=["layer"]) layer_updated = Signal(providing_args=["layer"]) layer_deleted = Signal(providing_args=["layer"])
gc.collect() def receiver_1_arg(val, **kwargs): return val class Callable: def __call__(self, val, **kwargs): return val def a(self, val, **kwargs): return val a_signal = Signal() b_signal = Signal() c_signal = Signal() d_signal = Signal(use_caching=True) class DispatcherTests(SimpleTestCase): def assertTestIsClean(self, signal): """Assert that everything has been cleaned up automatically""" # Note that dead weakref cleanup happens as side effect of using # the signal's receivers through the signals API. So, first do a # call to an API method to force cleanup. self.assertFalse(signal.has_listeners()) self.assertEqual(signal.receivers, []) @override_settings(DEBUG=True)
from django.dispatch import Signal User_logged_in = Signal(providing_args=['instance', 'request'])