def register_signal(self, providing_args): if self.is_signal_registered(): raise ValueError(f"Signal {self} already registered.") self.__before_service_signal = dispatch.Signal( providing_args=providing_args) self.__after_service_signal = dispatch.Signal( providing_args=providing_args + ['result']) self._connect_queued()
def returner(ret): ''' Signal a Django server that a return is available ''' signaled = dispatch.Signal(providing_args=['ret']).send(sender='returner', ret=ret) for signal in signaled: log.debug('Django returner function \'returner\' signaled {0} ' 'which responded with {1}'.format(signal[0], signal[1]))
def save_load(jid, load): ''' Save the load to the specified jid ''' signaled = dispatch.Signal(providing_args=['jid', 'load']).send( sender='save_load', jid=jid, load=load) for signal in signaled: log.debug('Django returner function \'save_load\' signaled {0} ' 'which responded with {1}'.format(signal[0], signal[1]))
def save_load(jid, load, minions=None): """ Save the load to the specified jid """ signaled = dispatch.Signal(providing_args=["jid", "load"]).send( sender="save_load", jid=jid, load=load) for signal in signaled: log.debug( "Django returner function 'save_load' signaled %s which responded with %s", signal[0], signal[1], )
def returner(ret): """ Signal a Django server that a return is available """ signaled = dispatch.Signal(providing_args=["ret"]).send(sender="returner", ret=ret) for signal in signaled: log.debug( "Django returner function 'returner' signaled %s which responded with %s", signal[0], signal[1], )
def __init__(self, providing_args=None): """ Due to how python manage class prototypes, there's a chance that class definition using register_service_signal will not be loaded until first import of given class. Therefore it's likely that binding function responsible for loading functions called before/after signal will be invoked before signal register. In this case functions are queued and connected to actual signal after the registration. Whether or not registration took place is defined by providing_args. If argument is None, signal is considered not registered. """ self.__signal_results = {'before': None, 'after': None} self.__connection_queue = { type_: queue.Queue() for type_ in ServiceSignalBindType } self.__signals_before = [] self.__signals_after = [] if not providing_args: self.__before_service_signal = None self.__after_service_signal = None else: self.__before_service_signal = dispatch.Signal( providing_args=providing_args) self.__after_service_signal = dispatch.Signal( providing_args=providing_args + ['result'])
tasks.signal_receiver.apply_async( args=[sender], kwargs=kwargs, default_retry_delay=SEND_RETRY_DELAY, max_retries=SEND_RETRY, queue=SIGNALS_QUEUE, ) else: SignalReceiver(sender, **kwargs).run() def initial_signals(): for signal in Signal.objects.filter(is_active=True): def_signal = getattr(signals, signal.signal) def_signal.connect(signal_receiver, sender=signal.model.model_class(), dispatch_uid=signal.model.name) pre_send = dispatch.Signal() post_send = dispatch.Signal() post_exception = dispatch.Signal() safari_push_package = dispatch.Signal() safari_subscribe = dispatch.Signal() safari_unsubscribe = dispatch.Signal() safari_error_log = dispatch.Signal() push_subscribe = dispatch.Signal() push_unsubscribe = dispatch.Signal()
from django.template import loader from django.dispatch import receiver from django.db.models.signals import post_save from django.contrib.auth.models import Permission, Group from django.contrib.sites.models import Site from django.utils.translation import ugettext as _ from django.urls import reverse from django.core.mail import EmailMultiAlternatives from viewflow.signals import flow_finished from viewflow.models import Task from michelin_bpm.main.views import UnblockClientView from michelin_bpm.main.utils import AgoraMailerClient client_unblocked = dispatch.Signal(providing_args=['proposal']) @receiver(client_unblocked, sender=UnblockClientView) def client_unblocked_handler(sender, proposal, **kwargs): # Проверяем, есть ли у текущей заявки процесс по созданию BibServe-аккаунта if hasattr(proposal, 'bibserveprocess'): proposal.bibserveprocess.is_allowed_to_activate = True proposal.bibserveprocess.save() @receiver(post_save, sender=Task) def task_created(sender, instance, created, **kwargs): EMAIL_ON_TASK_STARTED = [ 'approve_by_account_manager', 'approve_by_credit_manager',
#!/bin/env python # -*- coding:utf-8 -*- # created by hansz from django import dispatch # 定义查询数据库的信号 # 查询的 查询状态 查询时长 查询备注 query_db_signal = dispatch.Signal( providing_args=["status", "query_time", "message"])
DATE = ["DateField", "TimeField", "DateTimeField"] BOOLEAN = ["BooleanField", "NullBooleanField"] BOOLEAN_TRUE = [1, "1", "Y", "Yes", "yes", "True", "true", "T", "t"] # Adding Support for Django 1.9+ if StrictVersion(django.get_version()) >= StrictVersion("1.9.0"): DATE_INPUT_FORMATS = tuple(settings.DATE_INPUT_FORMATS) or ("%d/%m/%Y", "%Y/%m/%d") else: DATE_INPUT_FORMATS = settings.DATE_INPUT_FORMATS or ("%d/%m/%Y", "%Y/%m/%d") CSV_DATE_INPUT_FORMATS = DATE_INPUT_FORMATS + ("%d-%m-%Y", "%Y-%m-%d") cleancol = re.compile("[^0-9a-zA-Z]+") # cleancol.sub('_', s) from django import dispatch imported_csv = dispatch.Signal(providing_args=["instance", "row"]) importing_csv = dispatch.Signal(providing_args=["instance", "row"]) # Note if mappings are manually specified they are of the following form ... # MAPPINGS = "column1=shared_code,column2=org(Organisation|name),column3=description" # statements = re.compile(r";[ \t]*$", re.M) def save_csvimport(props=None, instance=None): """ To avoid circular imports do saves here """ try: if not instance: from csvimport.models import CSVImport csvimp = CSVImport()
# coding: utf-8 from django import dispatch on_before_logout = dispatch.Signal(providing_args=[])
""" Copyright 2015 Ricardo Tubio-Pardavila Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ __author__ = '*****@*****.**' from django import dispatch as dj_dispatch sn_loaded = dj_dispatch.Signal()
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 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/agpl-3.0.html. from django import dispatch from django.core.management.base import BaseCommand from django.contrib.auth.models import User from externalsites.models import account_models from teams.models import TeamNotificationSetting signal = dispatch.Signal(providing_args=['stdout']) class Command(BaseCommand): help = u'Setup the domain for the default site.' def handle(self, *args, **kwargs): self.stdout.write("deleting user emails...\n") User.objects.all().update(email='') self.stdout.write("removing external accounts...\n") for AccountModel in account_models: AccountModel.objects.all().delete() self.stdout.write("removing team notification settings...\n") TeamNotificationSetting.objects.all().delete() signal.send(self, stdout=self.stdout)
from django import dispatch stored_callback = dispatch.Signal( providing_args=['callback_instance', 'model_instance'], ) processed_callback = dispatch.Signal( providing_args=['callback_instance', 'model_instance'], ) error_callback = dispatch.Signal( providing_args=['callback_instance', 'model_instance'], )
] FLOAT = ['DecimalField', 'FloatField'] NUMERIC = INTEGER + FLOAT SMALLINT_DBS = [ 'sqlite3', ] DATE = ['DateField', 'TimeField', 'DateTimeField'] BOOLEAN = ['BooleanField', 'NullBooleanField'] BOOLEAN_TRUE = [1, '1', 'Y', 'Yes', 'yes', 'True', 'true', 'T', 't'] DATE_INPUT_FORMATS = settings.DATE_INPUT_FORMATS or ('%d/%m/%Y', '%Y/%m/%d') CSV_DATE_INPUT_FORMATS = DATE_INPUT_FORMATS + ('%d-%m-%Y', '%Y-%m-%d') cleancol = re.compile('[^0-9a-zA-Z]+') # cleancol.sub('_', s) from django import dispatch imported_csv = dispatch.Signal(providing_args=['instance', 'row']) importing_csv = dispatch.Signal(providing_args=['instance', 'row']) # Note if mappings are manually specified they are of the following form ... # MAPPINGS = "column1=shared_code,column2=org(Organisation|name),column3=description" # statements = re.compile(r";[ \t]*$", re.M) def save_csvimport(props=None, instance=None): """ To avoid circular imports do saves here """ try: if not instance: from csvimport.models import CSVImport csvimp = CSVImport() if props: for key, value in props.items():
from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cmsplugin_contact.utils import class_for_path try: from cms.plugins.text.settings import USE_TINYMCE except ImportError: USE_TINYMCE = False from models import Contact from forms import AkismetContactForm, RecaptchaContactForm, HoneyPotContactForm from admin import ContactAdminForm email_sent = dispatch.Signal(providing_args=[ "data", ]) class ContactPlugin(CMSPluginBase): model = Contact name = _("Contact Form") render_template = "cmsplugin_contact/contact.html" form = ContactAdminForm subject_template = "cmsplugin_contact/subject.txt" email_template = "cmsplugin_contact/email.txt" text_enabled = True fieldsets = ((None, { 'fields': ('form_name', 'form_layout', 'site_email', 'thanks', 'submit'),
from django import dispatch from django.contrib import messages from django.utils.translation import ugettext_lazy as _ from registration import signals as registration_signals from frontend.account import regbackend from frontend.account import utils # Argument is user which has logged in user_login = dispatch.Signal(providing_args=["request", "user"]) # Arugment is user which has logged out if any user_logout = dispatch.Signal(providing_args=["request", "user"]) def user_login_message(sender, request, user, **kwargs): """ Gives a success login message to the user. """ messages.success(request, _("You have been successfully logged in."), fail_silently=True) user_login.connect(user_login_message, dispatch_uid=__name__ + '.user_login_message') def set_language(sender, request, user, **kwargs):
# -*- coding: UTF-8 -*- from django import dispatch timetable_prepare = dispatch.Signal( providing_args=['timetable', 'tracks', 'events']) attendees_connected = dispatch.Signal( providing_args=['attendee1', 'attendee2']) # Issued when an event is booked (booked = True) or if the booking is canceled (booked=False) event_booked = dispatch.Signal( providing_args=['booked', 'event_id', 'user_id'])
from django_extensions.db.fields.json import JSONField from aa_stripe.exceptions import (StripeCouponAlreadyExists, StripeInternalError, StripeMethodNotAllowed, StripeWebhookAlreadyParsed, StripeWebhookParseError) from aa_stripe.settings import stripe_settings from aa_stripe.signals import stripe_charge_card_exception, stripe_charge_refunded, stripe_charge_succeeded from aa_stripe.utils import timestamp_to_timezone_aware_date USER_MODEL = getattr(settings, "STRIPE_USER_MODEL", settings.AUTH_USER_MODEL) logger = logging.getLogger("aa-stripe") # signals webhook_pre_parse = dispatch.Signal( providing_args=["instance", "event_type", "event_model", "event_action"]) class StripeBasicModel(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) stripe_response = JSONField(blank=True) class Meta: abstract = True class StripeCustomer(StripeBasicModel): user = models.ForeignKey(USER_MODEL, on_delete=models.CASCADE, related_name="stripe_customers")
from django import dispatch pre_sync = dispatch.Signal(providing_args=["client", "settings", "input_kwargs"]) post_sync = dispatch.Signal(providing_args=["client", "settings"])
# coding: utf-8 from django import dispatch bill_created = dispatch.Signal(providing_args=['bill']) bill_edited = dispatch.Signal(providing_args=['bill']) bill_moderated = dispatch.Signal(providing_args=['bill']) bill_processed = dispatch.Signal(providing_args=['bill']) bill_removed = dispatch.Signal(providing_args=['bill']) bill_ended = dispatch.Signal(providing_args=['bill'])
from django.db import models, transaction, IntegrityError from django.conf import settings from django import dispatch from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify from django.template.loader import render_to_string from django.core.mail import send_mail from django.utils.crypto import constant_time_compare from django.contrib.auth.forms import SetPasswordForm from django.contrib.auth.models import AbstractUser, UserManager from froide.helper.text_utils import replace_custom, replace_word from froide.helper.csv_utils import export_csv, get_dict user_activated_signal = dispatch.Signal(providing_args=[]) class User(AbstractUser): organization = models.CharField(_('Organization'), blank=True, max_length=255) organization_url = models.URLField(_('Organization URL'), blank=True, max_length=255) private = models.BooleanField(_('Private'), default=False) address = models.TextField(_('Address'), blank=True) terms = models.BooleanField(_('Accepted Terms'), default=True) newsletter = models.BooleanField(_('Wants Newsletter'), default=False) is_trusted = models.BooleanField(_('Trusted'), default=False)
def get_queryset(cls, queryset, user): queryset = cls.filter_queryset(queryset) # GraphQL calls with an info object while Rest calls with the user itself if isinstance(user, ResolveInfo): user = user.context.user if settings.ROW_SECURITY and user.is_anonymous: return queryset.filter(id=-1) if settings.ROW_SECURITY: dist = UserDistrict.get_user_districts(user._u) return queryset.filter(claim__health_facility__location_id__in=[ l.location_id for l in dist ]) return queryset signal_claim_rejection = dispatch.Signal(providing_args=["claim"]) class Claim(core_models.VersionedModel): id = models.AutoField(db_column='ClaimID', primary_key=True) uuid = models.CharField(db_column='ClaimUUID', max_length=36, default=uuid.uuid4, unique=True) category = models.CharField(db_column='ClaimCategory', max_length=1, blank=True, null=True) insuree = models.ForeignKey(insuree_models.Insuree, models.DO_NOTHING, db_column='InsureeID')
from django import dispatch from django.dispatch import receiver from notify.models import Notification from django.utils.translation import ugettext as _ import six notify = dispatch.Signal(providing_args=[ 'recipient', 'recipient_list', 'actor', 'actor_text', 'actor_url', 'verb', 'description', 'nf_type', 'target', 'target_text', 'target_url', 'obj', 'obj_text', 'obj_url', 'extra', ]) def truncate(string, length): if string is not None and isinstance(string, six.string_types): if len(string) > length: return string[:length] return string
# -*- coding:utf-8 -*- from django import dispatch # Creation of a new link between Django user and Loginza identity. # Parameters: # - sender - HttpRequest instance # - user_map - loginza.models.UserMap instance created = dispatch.Signal(providing_args=['user_map']) # Loginza athentication returned error # Parameters: # - sender - HttpRequest instance # - error - loginza.authentication.LoginzaError instance error = dispatch.Signal(providing_args=['error']) # Successfull completion Loginza authentication # Parameters: # - sender: HttpRequest instance # - user: authenticated (may be newly created) user # - identity: loginza identity (loginza.models.Identity) used for authentication # # A handler may return a HttpRespose instance which will be eventually # returned from the completion view. If omitted a standard redirect will be # used. authenticated = dispatch.Signal(providing_args=['user', 'identity']) # login_required decorator found that user is not logged in # Parameters: # - sender: HttpRequest instance # # A handler may return a HttpRespose instance which will be eventually
from __future__ import absolute_import from django import dispatch cas_user_authenticated = dispatch.Signal( providing_args=['user', 'created', 'attributes', 'ticket', 'service'], )
# Amara, universalsubtitles.org # # Copyright (C) 2013 Participatory Culture Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # 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/agpl-3.0.html. """Signals for the subtitles app. """ from django import dispatch language_deleted = dispatch.Signal() # Called when when subtitles are "completed". # - Most of the time this the publish action occurs. # - For tasks, this is when all tasks are complete # - Note that this signal may can multiple times for a single # SubtitleLanguage subtitles_completed = dispatch.Signal() # Called when we have a new public/complete version subtitles_published = dispatch.Signal(providing_args=['version'])
# -*- coding: utf-8 -*- # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2021-present Kaleidos Ventures SL from django import dispatch from django.apps import AppConfig signal_assigned_to = dispatch.Signal(providing_args=["user", "obj"]) signal_assigned_users = dispatch.Signal( providing_args=["user", "obj", "new_assigned_users"]) signal_watchers_added = dispatch.Signal( providing_args=["user", "obj", "new_watchers"]) signal_members_added = dispatch.Signal( providing_args=["user", "project", "new_members"]) signal_mentions = dispatch.Signal(providing_args=["user", "obj", "mentions"]) signal_comment = dispatch.Signal(providing_args=["user", "obj", "watchers"]) signal_comment_mentions = dispatch.Signal( providing_args=["user", "obj", "mentions"]) class NotificationsAppConfig(AppConfig): name = "taiga.projects.notifications" verbose_name = "Notifications" def ready(self): from . import signals as handlers signal_assigned_to.connect(handlers.on_assigned_to) signal_assigned_users.connect(handlers.on_assigned_users)
""" Signals for this app are: post_app_install, post_app_uninstall, post_app_copy. post_app_install, post_app_uninstall Sent when an app is installed or uninstalled from an environment, with sender=environment, and app=the app. post_app_copy Sent when an app is copied, with sender=environment, source_app=the app that is copied and new_app=the new, freshly copied app. """ from django import dispatch __all__ = ('post_app_install', 'post_app_uninstall', 'post_app_copy') post_app_install = dispatch.Signal(providing_args=['app']) post_app_uninstall = dispatch.Signal(providing_args=['app']) post_app_copy = dispatch.Signal(providing_args=['source_app', 'new_app'])
super(ModelRelatedField, self).__init__(**kwargs) class DictField(serializers.CharField): def to_internal_value(self, data): return (data if (isinstance(data, (six.string_types, six.text_type)) or isinstance(data, (dict, list))) else self.fail("Unknown type.")) def to_representation(self, value): return (json.loads(value) if not isinstance(value, (dict, list)) else value) api_pre_save = dispatch.Signal(providing_args=["instance", "user"]) api_post_save = dispatch.Signal(providing_args=["instance", "user"]) def with_signals(func): ''' Decorator for send api_pre_save and api_post_save signals from serializers. ''' def func_wrapper(*args, **kwargs): user = args[0].context['request'].user with transaction.atomic(): instance = func(*args, **kwargs) api_pre_save.send(sender=instance.__class__, instance=instance, user=user) with transaction.atomic():