def handle(self, *args, **options): # If we're running in a migrations we need to use the correct apps self.apps = options.get('apps', apps) sources = options.get('sources') sources_dir = os.path.join(share.__path__[0], SOURCES_DIR) if sources: source_dirs = [os.path.join(sources_dir, s) for s in sources] else: source_dirs = [ os.path.join(sources_dir, s) for s in os.listdir(sources_dir) ] if self.apps.get_model('share.ShareUser').__module__ == '__fake__': receiver( post_save, sender=self.apps.get_model('share.ShareUser'), dispatch_uid='__fake__.share.models.share_user_post_save_handler' )(user_post_save) with transaction.atomic(): self.known_harvesters = self.sync_drivers( 'share.harvesters', self.apps.get_model('share.Harvester')) self.known_transformers = self.sync_drivers( 'share.transformers', self.apps.get_model('share.Transformer')) self.update_sources(source_dirs, overwrite=options.get('overwrite'))
def register(cls): cls._handle_status_change = partial(cls.handle, signal=cls.orm_model.STATUS_CHANGE) receiver(cls.orm_model.STATUS_CHANGE, sender=cls.orm_model)(cls._handle_status_change) cls.logger.debug("Registered status_change handlers for %s", cls.orm_model)
def ready(self): # Signals from volunteer.apps.profiles.receivers import ( create_volunteer_profile, ) dispatch.receiver(post_save, sender=settings.AUTH_USER_MODEL)( create_volunteer_profile, )
def initialise(self, obj, *args, **kwargs): class_name = obj.get_class(cls) obj.methods[class_name] = ( decorated, prefetch, ) obj.signals[class_name] = signals receiver(signals, sender=class_name)(obj.propogate_signal) self.obj = obj
def register(cls): cls._handle_post_save = partial(cls.handle, signal=post_save) receiver(post_save, sender=cls.orm_model)(cls._handle_post_save) cls._handle_post_delete = partial(cls.handle, signal=post_delete) receiver(post_delete, sender=cls.orm_model)(cls._handle_post_delete) cls.logger.debug("Registered post_save + post_delete handlers for %s", cls.orm_model)
def as_routes(cls, **kwargs): if 'queryset' in kwargs: model = kwargs['queryset'].model else: model = kwargs.get('model') or cls.model or cls.queryset.model dispatch_uid = _md5(str(cls) + str(kwargs)) kwargs['_uid'] = dispatch_uid receiver(post_save, sender=model, weak=False, dispatch_uid=dispatch_uid)(partial(cls._post_save, **kwargs)) receiver(post_delete, sender=model, weak=False, dispatch_uid=dispatch_uid)(partial(cls._post_delete, **kwargs)) return super(ObjectSubscribeConsumers, cls).as_routes(**kwargs)
def test_anonymize(user): handler = Mock() receiver(anonymize, sender=user.__class__)(handler) handler.assert_not_called() user.anonymize() handler.assert_called_once_with( signal=anonymize, sender=user.__class__, instance=user, )
def load_location_receivers(sender): """ enables signal listening when called designed to be called in AppConfig subclasses """ # using decorator pattern with old syntax # in order to decorate an existing function receiver(post_save, sender=sender, dispatch_uid='ws_update_mobile_location')(update_mobile_location)
def bind_model_cached_manager_signal(model_package): """ 自动为model注册缓存清除钩子 :param model_package: model包 :return: """ for __model in model_package.__all__: m = getattr(model_package, __model) if isinstance(getattr(m, 'objects'), HoHoCacheFactory): receiver(post_save, sender=m)(delete_model_single_object_cache) receiver(post_delete, sender=m)(delete_model_single_object_cache)
def ready(self): # Signals from mozy.apps.mosaic.receivers import ( create_source_tiles, create_stock_tiles, ) dispatch.receiver(post_save, sender='mosaic.NormalizedSourceImage')( create_source_tiles, ) dispatch.receiver(post_save, sender='mosaic.NormalizedStockImage')( create_stock_tiles, )
def ready(self): from nsc.review.models import Review, ReviewRecommendation receiver(post_save, sender=Review)(clear_cache) receiver(post_delete, sender=Review)(clear_cache) receiver(post_save, sender=ReviewRecommendation)(clear_cache) receiver(post_delete, sender=ReviewRecommendation)(clear_cache)
def __new__(mcs, name, bases, attrs, **kwargs): if "__slots__" not in attrs: attrs['__slots__'] = () if "__unicode__" in attrs and '__str__' not in attrs: attrs['__str__'] = _get_unicode extra_metadata: dict = {**default_extra_metadata} meta = None if "Meta" in attrs: meta = attrs['Meta'] extra_metadata['proxy'] = getattr(meta, 'proxy', False) if not getattr(meta, 'abstract', False): for extra_name in filter( lambda y: hasattr(meta, y), map(lambda x: f'_{x}', extra_metadata.keys())): extra_metadata[extra_name[1:]] = getattr(meta, extra_name) attrs['__extra_metadata__'] = deepcopy(extra_metadata) model_class = super(ModelBaseClass, mcs).__new__(mcs, name, bases, attrs, **kwargs) model_class.OriginalMeta = meta if meta is not None else model_class.Meta if hasattr(model_class, '__prepare_model__'): model_class.__prepare_model__() if getattr(model_class, '_cache_responses', False): receiver(post_save, sender=model_class)(update_cache_for_model) receiver(post_delete, sender=model_class)(update_cache_for_model) cache_related_labels = getattr(model_class, '_cache_related_labels', ()) update_cache_for_model_related = partial( update_cache_for_model, cached_model_class=model_class) for label in cache_related_labels: receiver(post_save, sender=label)(update_cache_for_model_related) receiver(post_delete, sender=label)(update_cache_for_model_related) return model_class
def class_prepared_signal_handler(sender, **kwargs): if sender.__name__ == "ActionItem": register = receiver( models.signals.post_save, sender=sender, dispatch_uid="publicweb.models.actionitem_signal_handler") register(actionitem_signal_handler)
def test_game_announcement_signal(self): game_played_receiver = receiver(game_played)(mock.Mock()) game = Game.objects.announce(self.users[0], self.users[1], self.default_competition) game_played_receiver.assert_called_once_with(sender=game, signal=mock.ANY) # Check that the 'game played' signal is fired only when the game # object is created, not modified game_played_receiver = receiver(game_played)(mock.Mock()) game.date = timezone.now() game.save() self.assertEqual(game_played_receiver.call_count, 0)
def test_save_new_competition_sends_created_signal(self): competition_created_receiver = receiver(competition_created)( mock.Mock()) competition = CompetitionFactory() competition_created_receiver.assert_called_once_with( sender=competition, signal=mock.ANY)
def register(self, model, field, build_filter=None): def add_to_queue(sender, instance, field, **kwargs): payload = dict( model=str(model._meta), pk=instance.pk, field=field, bucket=getattr(settings, 'MUTO_AWS_STORAGE_BUCKET_NAME', getattr(settings, 'AWS_STORAGE_BUCKET_NAME')), key=str(getattr(instance, field)), versions=[], callback_url=getattr(settings, 'MUTO_CALLBACK_URL', None), ) if callable(build_filter): filter = build_filter(instance) image_version_definitions = ImageVersionDefinition.objects.filter(filter) else: image_version_definitions = ImageVersionDefinition.objects.all() for ivd in image_version_definitions: payload['versions'].append(dict( identifier=ivd.identifier, options=ivd.options, )) self.redis.lpush('muto:queue', json.dumps(payload)) self.redis.publish('muto:queue', 'PUSH') func = curry(add_to_queue, field=field) rcvr = receiver(post_save, sender=model)(func) self.registry.append(dict( receiver=rcvr, model=model, field=field, ))
def on(event, *args, **kwargs): deprecation_reason = getattr(event, "_deprecation_reason", None) if deprecation_reason: # pragma: no cover warn(deprecation_reason, DeprecationWarning) return receiver(event, *args, **kwargs)
def event_receiver_decorator(fn): try: sender = ContentType.objects.get(model=content_type).model_class() except ContentType.DoesNotExist: sender = None dispatch_uid = '%s_%s_%s' % (fn.__name__, content_type, type_) wrapper = receiver(signal, sender=sender, dispatch_uid=dispatch_uid) return wrapper(fn)
def test_game_announcement_signal(self): game_played_receiver = receiver(game_played)(mock.Mock()) game = Game.objects.announce(self.users[0], self.users[1], self.default_competition) game_played_receiver.assert_called_once_with( sender=game, signal=mock.ANY ) # Check that the 'game played' signal is fired only when the game # object is created, not modified game_played_receiver = receiver(game_played)(mock.Mock()) game.date = timezone.now() game.save() self.assertEqual(game_played_receiver.call_count, 0)
def ready(self): shard_settings = getattr(settings, 'DJANGO_SHARDING_SETTINGS', {}) shard_groups = [settings.DATABASES[db_settings]['SHARD_GROUP'] for db_settings in settings.DATABASES] shard_groups = set(filter(lambda group: group is not None, shard_groups)) self.bucketers = {} self.routing_strategies = {} for shard_group in shard_groups: group_settings = shard_settings.get(shard_group, {}) self.bucketers[shard_group] = group_settings.get( 'BUCKETING_STRATEGY', RoundRobinBucketingStrategy(shard_group=shard_group, databases=settings.DATABASES) ) self.routing_strategies[shard_group] = group_settings.get( 'ROUTING_STRATEGY', PrimaryOnlyRoutingStrategy(databases=settings.DATABASES) ) # Unless otherwise instructed, add the signal to save the shard to the model if it has a shard field. for model in apps.get_models(): if getattr(model, 'django_sharding__stores_shard', False) and getattr(model, 'django_sharding__shard_group', None): shard_group = getattr(model, 'django_sharding__shard_group', None) shard_field = getattr(model, 'django_sharding__shard_field', None) if not shard_field: raise Exception('The model {} must have a `shard_field` attribute'.format(model)) else: shard_fields = list(filter(lambda field: getattr(field, 'django_sharding__stores_shard', False), model._meta.fields)) if not any(shard_fields): continue if len(shard_fields) > 1: raise Exception('The model {} has multuple fields for shard storage: {}'.format(model, shard_fields)) shard_field = shard_fields[0] shard_group = getattr(shard_field, 'django_sharding__shard_group', None) if not shard_group: raise Exception('The model {} with the shard field must have a `shard_group` attribute'.format(model)) if not getattr(shard_field, 'django_sharding__use_signal', False): continue group_settings = shard_settings.get(shard_group, {}) if group_settings.get('SKIP_ADD_SHARDED_SIGNAL', False): continue receiver(models.signals.pre_save, sender=model)(save_shard_handler)
def test_save_existing_competition_doesnt_send_created_signal(self): competition = CompetitionFactory() competition_created_receiver = receiver(competition_created)( mock.Mock()) competition.name = 'Foobar' competition.save() competition_created_receiver.assert_not_called()
def handle(self, *args, **options): # If we're running in a migrations we need to use the correct apps self.apps = options.get('apps', apps) sources = options.get('sources') sources_dir = os.path.join(share.__path__[0], SOURCES_DIR) if sources: source_dirs = [os.path.join(sources_dir, s) for s in sources] else: source_dirs = [os.path.join(sources_dir, s) for s in os.listdir(sources_dir)] if self.apps.get_model('share.ShareUser').__module__ == '__fake__': receiver(post_save, sender=self.apps.get_model('share.ShareUser'), dispatch_uid='__fake__.share.models.share_user_post_save_handler')(user_post_save) with transaction.atomic(): self.known_harvesters = self.sync_drivers('share.harvesters', self.apps.get_model('share.Harvester')) self.known_transformers = self.sync_drivers('share.transformers', self.apps.get_model('share.Transformer')) self.update_sources(source_dirs, overwrite=options.get('overwrite'))
def complex_setting_changed(**kwargs): if kwargs['enter'] and kwargs['setting'] in COMPLEX_OVERRIDE_SETTINGS: # Considering the current implementation of the signals framework, # this stacklevel shows the line containing the override_settings call. warnings.warn("Overriding setting %s can lead to unexpected behavior." % kwargs['setting'], stacklevel=6) @receiver(setting_changed)
def wrap(func): func = shoutout(func) from django import dispatch return dispatch.receiver( *args, weak=kwargs.pop('weak', False), dispatch_uid=kwargs.pop('dispatch_uid', '%s.%s' % (func.__module__, func.__name__)), **kwargs)(func)
def indexing_receiver(signal, signal_name): """Return a routine that registers signal handlers for indexers. The returned registration routine uses strong refs, makes up a dispatch_uid, and uses ``sender_class`` as the sender. """ return receiver(signal, sender=sender_class, dispatch_uid='%s.%s.elastic.%s' % (app, sender_class.__name__, signal_name), weak=False)
def receiver(self, signal_name): """ A wrapper for django.dispatch.receiver. Takes a signal name which has to be registered already. """ receiver_wrapper = receiver(signal=self.signals[signal_name]) @wraps(receiver_wrapper) def wrapper(func): return receiver_wrapper(func) return wrapper
def indexing_receiver(signal, signal_name): """Return a routine that registers signal handlers for indexers. The returned registration routine uses strong refs, makes up a dispatch_uid, and uses ``sender_class`` as the sender. """ return receiver( signal, sender=sender_class, dispatch_uid='{0!s}.{1!s}.elastic.{2!s}'.format(app, sender_class.__name__, signal_name), weak=False)
def _dec(rule): receiver_kwargs = {} if model is not None: receiver_kwargs['sender'] = getattr(models, model) def handler(sender, **kwargs): if kwargs.get('raw', False): return # since the rule knows what model the signal comes from # the sender value is redundant. rule(kwargs['instance']) else: def handler(sender, **kwargs): if kwargs.get('raw', False): return rule(sender, kwargs['instance']) return receiver(getattr(signals, signal), **receiver_kwargs)(handler)
def test_ranking_changed_signal(self): ranking_changed_receiver = receiver(ranking_changed)(mock.Mock()) christoph, laurent, rolf = (UserFactory() for i in range(3)) game1 = self.default_competition.add_game(rolf, christoph) game2 = self.default_competition.add_game(christoph, rolf) self.default_competition.add_game(christoph, rolf) self.assertEqual(ranking_changed_receiver.call_count, 4) args_list = ranking_changed_receiver.call_args_list self.assertEqual(args_list, [ mock.call(player=rolf, old_ranking=None, sender=game1, new_ranking=1, signal=mock.ANY, competition=self.default_competition), mock.call(player=christoph, old_ranking=None, sender=game1, new_ranking=2, signal=mock.ANY, competition=self.default_competition), mock.call(player=christoph, old_ranking=2, sender=game2, new_ranking=1, signal=mock.ANY, competition=self.default_competition), mock.call(player=rolf, old_ranking=1, sender=game2, new_ranking=2, signal=mock.ANY, competition=self.default_competition), ])
grouping = models.CharField(_('grouping'), default="", blank=True, max_length=255, choices=( ('', _('default'),), ('main_menu', _('main_menu')), ('main_category', _('main_category')), )) text_entity_fields = common.TextEntity.text_entity_fields + ['parent', 'name', 'action', 'grouping'] @classmethod def get_main(cls): return cls.objs.filter(grouping="main_menu") @common.memoize_field('_articles') def get_articles(self): return Article.objs.filter(parent=self).prefetch_related('attachments').select_related() objs = SectionManager() receiver(post_save, sender=Section)(common.make_full_path_signal) class Article(common.LeafEntity, common.TextEntity, common.SeoEntity): class Meta: verbose_name = _('article') verbose_name_plural = _('articles') short = RichTextField(_('short'), blank=True) parent = TreeForeignKey(Section, verbose_name=_('parent')) other_info = models.TextField(_('other_info'), null=True, default="")
def get_subs(self): return CatalogManager.query_wrapper(self.get_children()) def get_catalog_tiles(self): max_len = 4 tiles = [] subs = CatalogManager.query_wrapper(self.get_children()).order_by('?')[:max_len] if subs: tiles = tiles + list(subs) tiles_len = len(tiles) if tiles_len >= max_len: return tiles return tiles + list(self.get_products().order_by('?')[:max_len - tiles_len]) receiver(post_save, sender=Catalog)(common.make_full_path_signal) class CategoryManager(common.TextEntityManager): pass class Category(Section): objs = CategoryManager() @classmethod def get_main(cls): return cls.objs.filter(grouping="main_category") @classmethod def get_other(cls): return cls.objs.filter(grouping="")
def add_dedupe_signals(cls): """Class decorator to add signals needed to dedupe.""" receiver(pre_save, sender=cls)(revert_dedupe) receiver(post_save, sender=cls)(apply_dedupe) receiver(pre_delete, sender=cls)(revert_dedupe) return cls
def contribute_to_class(self, cls, name): super(FilesField, self).contribute_to_class(cls, name) receiver(post_save, sender=cls)(manage_files_on_disk) setattr(cls, self.name, controllers.FilesDescriptor(self))
if created and not user.manager: from profile.models import Manager today = datetime.date.today() available_managers = Manager.objects.filter( is_available_for_new_users=True) user.manager = available_managers.exclude( managed_users__date_joined__gt=today).order_by('id').first() if not user.manager: user.manager = available_managers.filter( managed_users__date_joined__gt=today).annotate( users=Count('managed_users')).order_by('users').first() user.save() receiver(post_save, sender=User)(post_save_clean_image_file) receiver(post_delete, sender=User)(post_delete_clean_image_file) class UserPhone(models.Model): class Meta: verbose_name = u'телефон пользователя' verbose_name_plural = u'телефоны пользователя' unique_together = (('phone', 'user'), ) ordering = ['order'] phone = models.ForeignKey('ad.Phone', verbose_name=u'телефон', related_name='users_m2m') user = models.ForeignKey(User, verbose_name=u'пользователь',
class Meta: model = Sponsorship fields = '__all__' widgets = { 'organization': ModelSelect2Widget(data_view='organization-lookup', attrs=SELECT2_SIDEBAR), 'event': ModelSelect2Widget(data_view='event-lookup', attrs=SELECT2_SIDEBAR), 'contact': ModelSelect2Widget(data_view='person-lookup', attrs=SELECT2_SIDEBAR), } # ---------------------------------------------------------- # Signals # adding @receiver decorator to the function defined in `workshops.forms` form_saved_add_comment = receiver( create_comment_signal, sender=OrganizationCreateForm, )(form_saved_add_comment) # adding @receiver decorator to the function defined in `workshops.forms` form_saved_add_comment = receiver( create_comment_signal, sender=MembershipCreateForm, )(form_saved_add_comment)
class NutritionStocksR(AbstractNutritionStocksR): REPORTING_TYPE = PERIODICAL_SOURCE RECEIPT_FORMAT = "{period__year_short}{period__month}" \ "NUTST-{dow}/{entity__slug}-{rand}" UNIQUE_TOGETHER = [('period', 'entity')] class Meta: app_label = 'snisi_nutrition' verbose_name = _("Nutrition Inputs Report") verbose_name_plural = _("Nutrition Inputs Reports") receiver(pre_save, sender=NutritionStocksR)(pre_save_report) receiver(post_save, sender=NutritionStocksR)(post_save_report) reversion.register(NutritionStocksR) class AggNutritionStocksR(AbstractNutritionStocksR, PeriodicAggregatedReportInterface, SNISIReport): REPORTING_TYPE = PERIODICAL_AGGREGATED RECEIPT_FORMAT = "{period__year_short}{period__month}" \ "NUTSTa-{dow}/{entity__slug}-{rand}" INDIVIDUAL_CLS = NutritionStocksR UNIQUE_TOGETHER = [('period', 'entity')] class Meta:
# 结束时间 end_time = models.FloatField(default=0.0) # 创建时间 create_time = TimeStampField(auto_now_add=True) # 最后更新时间 update_time = TimeStampField(auto_now=True) # 重构管理器 objects = HoHoModelManager() def __str__(self): return "[%s] 标题:%s, 归属协会%s" % (self.id, self.title, self.association.name) receiver(post_save, sender=AssociationAttendance)(delete_model_single_object_cache) receiver(post_delete, sender=AssociationAttendance)(delete_model_single_object_cache) receiver(post_save, sender=Association)(delete_model_single_object_cache) receiver(post_delete, sender=Association)(delete_model_single_object_cache) receiver(post_save, sender=AssociationDepartment)(delete_model_single_object_cache) receiver(post_delete, sender=AssociationDepartment)(delete_model_single_object_cache) receiver(post_save, sender=AssociationAccount)(delete_model_single_object_cache) receiver(post_delete, sender=AssociationAccount)(delete_model_single_object_cache)
#-*- coding: utf-8 -*- import urllib2 import urlparse from django.db.models.signals import post_save, pre_delete from django.core.cache import cache from django.dispatch import receiver from models import Comment def update_comments_count(sender, **kwargs): instance = kwargs['instance'] target = instance.content_object if target and hasattr(target, 'update_comments_count'): target.update_comments_count() receiver(post_save, sender=Comment, dispatch_uid='zavtra.comments.signals')(update_comments_count) receiver(pre_delete, sender=Comment, dispatch_uid='zavtra.comments.signals')(update_comments_count)
class SponsorshipForm(WidgetOverrideMixin, forms.ModelForm): helper = BootstrapHelper(submit_label='Add') class Meta: model = Sponsorship fields = '__all__' widgets = { 'organization': ModelSelect2(url='organization-lookup'), 'event': ModelSelect2(url='event-lookup'), 'contact': ModelSelect2(url='person-lookup'), } # ---------------------------------------------------------- # Signals # adding @receiver decorator to the function defined in `workshops.forms` form_saved_add_comment = receiver( create_comment_signal, sender=OrganizationCreateForm, )(form_saved_add_comment) # adding @receiver decorator to the function defined in `workshops.forms` form_saved_add_comment = receiver( create_comment_signal, sender=MembershipCreateForm, )(form_saved_add_comment)
from django.db.models.signals import post_save, m2m_changed, post_delete from django.contrib.flatpages.models import FlatPage from .blog.models import Entry from .gallery.models import Picture from .links.models import Link def get_pages_cache(): try: return caches['pages'] except KeyError: try: return caches['default'] except KeyError: return None def invalidate_cache(**kwargs): cache = get_pages_cache() if cache: cache.clear() # Register Receivers for for cleaning the cache _signals = (post_save, m2m_changed, post_delete) for _model in (FlatPage, Entry, Picture, Link): receiver(_signals, sender=_model)(invalidate_cache) del _signals del _model
umi = user.default_info elif type(item) is Message: msg = item umi = msg.user_message_info user = umi.user return msg, umi, user @staticmethod def delete_content_object(sender, instance, **kwargs): try: instance.content_object.delete() except: pass receiver(post_delete, sender=Token)(Token.delete_content_object) class HasTokenMixin(object): @property def verification_link(self): ctype = ContentType.objects.get_for_model(self) return Token.objects.get(content_type=ctype, object_id=self.pk).link() @property def token_key(self): ctype = ContentType.objects.get_for_model(self) return Token.objects.get(content_type=ctype, object_id=self.pk).key @staticmethod
class URENAMNutritionR(AbstractURENAMNutritionR): REPORTING_TYPE = PERIODICAL_SOURCE RECEIPT_FORMAT = "{period__year_short}{period__month}" \ "NAM-{dow}/{entity__slug}-{rand}" UNIQUE_TOGETHER = [('period', 'entity')] class Meta: app_label = 'snisi_nutrition' verbose_name = _("URENAM Report") verbose_name_plural = _("URENAM Reports") receiver(pre_save, sender=URENAMNutritionR)(pre_save_report) receiver(post_save, sender=URENAMNutritionR)(post_save_report) reversion.register(URENAMNutritionR) class AggURENAMNutritionR(AbstractURENAMNutritionR, PeriodicAggregatedReportInterface, SNISIReport): REPORTING_TYPE = PERIODICAL_AGGREGATED RECEIPT_FORMAT = "{period__year_short}{period__month}" \ "NAMa-{dow}/{entity__slug}-{rand}" INDIVIDUAL_CLS = URENAMNutritionR UNIQUE_TOGETHER = [('period', 'entity')] class Meta:
rc = ReportClass.objects.get(cls=self.report_cls, report_type=self.REPORTING_TYPE) except: return short_class_str(self.report_cls) return rc.name def as_xls(self): return default_xls_export(self) @classmethod def is_aggregated(cls): return cls.REPORTING_TYPE in (PERIODICAL_AGGREGATED, OCCASIONAL_AGGREGATED) # we need to ensure non-handled reports gets created with a correct receipt receiver(pre_save, sender=SNISIReport)(pre_save_report_incomplete) receiver(post_save, sender=SNISIReport)(post_save_report) reversion.register(SNISIReport) class PeriodicAggregatedReportInterface(models.Model): class Meta: abstract = True INDIVIDUAL_CLS = None PERIODIC_AGG_MIXIN_FIELDS = ['nb_source_reports_expected', 'nb_source_reports_arrived', 'nb_source_reports_arrived_on_time',
from django.db.models.signals import post_save, pre_delete from django.db import models from django.dispatch import receiver from django.core.cache import cache from models import Ware, Variant, Category def recalc_prices(sender, **kwargs): ware = kwargs['instance'].ware prices = ware.variants.aggregate(models.Min('price'),models.Max('price')) Ware.objects.filter(id=ware.id).update(min_price=prices['price__min'], max_price=prices['price__max']) def update_categories_cache(sender, **kwargs): cache.delete('categories') receiver(post_save, sender=Variant, dispatch_uid='shop.recalc_prices')(recalc_prices) receiver(pre_delete, sender=Variant, dispatch_uid='shop.recalc_prices')(recalc_prices) receiver(post_save, sender=Category, dispatch_uid='shop.categories_cache_update')(update_categories_cache) receiver(pre_delete, sender=Category, dispatch_uid='shop.categories_cache_update')(update_categories_cache)
""" if instance.file.name: instance.file.storage.delete(instance.file.name) if isinstance(instance, Video) and instance.preview.name: instance.preview.storage.delete(instance.preview.name) def delete_media_old_file_on_model_change(sender, instance, **kwargs): """ Deletes old file if object file has been changed. :param sender: :param instance: :param kwargs: :return: """ if instance.file_changed and instance._old_file is not None and instance._old_file.name: instance._old_file.storage.delete(instance._old_file.name) # Register media files deletion on model deletion receiver(models.signals.post_delete, sender=Video)(delete_media_file_on_model_delete) receiver(models.signals.post_delete, sender=VideoStream)(delete_media_file_on_model_delete) receiver(models.signals.post_delete, sender=Audio)(delete_media_file_on_model_delete) receiver(models.signals.post_delete, sender=AudioStream)(delete_media_file_on_model_delete) # Register media files deletion on model changing receiver(models.signals.pre_save, sender=Video)(delete_media_old_file_on_model_change) receiver(models.signals.pre_save, sender=VideoStream)(delete_media_old_file_on_model_change) receiver(models.signals.pre_save, sender=Audio)(delete_media_old_file_on_model_change) receiver(models.signals.pre_save, sender=AudioStream)(delete_media_old_file_on_model_change)
from base64 import b64encode generate_uid = lambda: \ b64encode( randrange(64**Survey.UID_LENGTH)\ .to_bytes(-(-Survey.UID_LENGTH * 6 // 8), byteorder='big') )\ .decode('ascii').replace('+', '-').replace('/', '_') uid = generate_uid() while Survey.objects.filter(uid=uid).exists(): uid = generate_uid() instance.uid = uid receiver(signals.pre_save, sender=Survey, weak=False)(signal) # Set species and dummy boolean for Section & End for n, c in inspect.getmembers( sys.modules[__name__], lambda o: inspect.isclass(o) and \ re.match(r'^(Section|End)$', o.__name__) ): def signal(sender, instance, *args, **kwargs): instance.species = sender.__name__ if instance.dummy is None: instance.dummy = sender.__name__ == 'End' receiver(signals.pre_save, sender=c, weak=False)(signal)
def ready(self): from bughouse.receivers import compute_ratings dispatch.receiver(post_save, sender='bughouse.Game')( compute_ratings, )
from member.models import Member, MemberUrlType, MemberUrl from service.models import Service from technology.models import Technology, TechnologySection from .views import get_last_modified_key def set_last_updated_at(sender, instance, created, **kwargs): """ Signal to set last_updated_at which is used for caching """ model_key = get_last_modified_key(sender) cache.set(model_key, datetime.datetime.now(), None) receiver(post_save, sender=Client)(set_last_updated_at) receiver(post_save, sender=Service)(set_last_updated_at) def set_last_updated_at_member(sender, instance, created, **kwargs): """ Signal to set last_updated_at which is used for caching """ model_key = get_last_modified_key(Member) cache.set(model_key, datetime.datetime.now(), None) receiver(post_save, sender=Member)(set_last_updated_at_member) receiver(post_save, sender=MemberUrl)(set_last_updated_at_member) receiver(post_save, sender=MemberUrlType)(set_last_updated_at_member)
class Administrator(User): token_prefix = 'admin' objects = AdministratorManager() class Meta: proxy = True def save(self, *args, **kwargs): self.type = User.Type.ADMINISTRATOR self.is_staff = True super(Administrator, self).save(*args, **kwargs) receiver(post_save, sender=Administrator)(create_login_link) class RegularUserManager(UserManager): def get_queryset(self): return super(RegularUserManager, self).get_queryset().filter( type=User.Type.REGULAR ) class RegularUser(User): token_prefix = 'user' objects = RegularUserManager() class Meta: proxy = True
max_length=500, null=True, blank=True) female_condoms_observation = models.CharField( max_length=500, null=True, blank=True) hiv_tests_observation = models.CharField( max_length=500, null=True, blank=True) pregnancy_tests_observation = models.CharField( max_length=500, null=True, blank=True) emergency_controls_observation = models.CharField( max_length=500, null=True, blank=True) receiver(pre_save, sender=PFActivitiesR)(pre_save_report) receiver(post_save, sender=PFActivitiesR)(post_save_report) reversion.register(PFActivitiesR, follow=['snisireport_ptr']) class AggPFActivitiesR(PFActivitiesRIface, PeriodicAggregatedReportInterface, SNISIReport): REPORTING_TYPE = PERIODICAL_AGGREGATED INDIVIDUAL_CLS = PFActivitiesR RECEIPT_FORMAT = "AMP{id}/{entity__slug}-{day}" UNIQUE_TOGETHER = [('period', 'entity')] class Meta: app_label = 'snisi_reprohealth'
self.magnesium_sulfate = magnesium_sulfate self.metronidazole = metronidazole self.oxytocine = oxytocine self.ceftriaxone_500 = ceftriaxone_500 self.ceftriaxone_1000 = ceftriaxone_1000 def fp_stockout_3methods(self): w = 0 for f in ('male_condom', 'female_condom', 'oral_pills', 'injectable', 'iud', 'implants', 'female_sterilization', 'male_sterilization'): if getattr(self, f) == 0: w += 1 return w >= 3 receiver(pre_save, sender=RHProductsR)(pre_save_report) receiver(post_save, sender=RHProductsR)(post_save_report) reversion.register(RHProductsR) class AggRHProductsR(PeriodicAggregatedReportInterface, SNISIReport): REPORTING_TYPE = PERIODICAL_AGGREGATED INDIVIDUAL_CLS = RHProductsR UNIQUE_TOGETHER = [('period', 'entity')] class Meta: app_label = 'snisi_reprohealth' verbose_name = _("Aggregated RH Commodities Report") verbose_name_plural = _("Aggregated RH Commodities Reports")
def ready(self): shard_settings = getattr(settings, 'DJANGO_SHARDING_SETTINGS', {}) shard_groups = [ settings.DATABASES[db_settings]['SHARD_GROUP'] for db_settings in settings.DATABASES ] shard_groups = set( filter(lambda group: group is not None, shard_groups)) self.bucketers = {} self.routing_strategies = {} for shard_group in shard_groups: group_settings = shard_settings.get(shard_group, {}) self.bucketers[shard_group] = group_settings.get( 'BUCKETING_STRATEGY', RoundRobinBucketingStrategy(shard_group=shard_group, databases=settings.DATABASES)) self.routing_strategies[shard_group] = group_settings.get( 'ROUTING_STRATEGY', PrimaryOnlyRoutingStrategy(databases=settings.DATABASES)) # Unless otherwise instructed, add the signal to save the shard to the model if it has a shard field. for model in apps.get_models(): if getattr(model, 'django_sharding__stores_shard', False) and getattr( model, 'django_sharding__shard_group', None): shard_group = getattr(model, 'django_sharding__shard_group', None) shard_field = getattr(model, 'django_sharding__shard_field', None) if not shard_field: raise Exception( 'The model {} must have a `shard_field` attribute'. format(model)) else: shard_fields = list( filter( lambda field: getattr( field, 'django_sharding__stores_shard', False), model._meta.fields)) if not any(shard_fields): continue if len(shard_fields) > 1: raise Exception( 'The model {} has multiple fields for shard storage: {}' .format(model, shard_fields)) shard_field = shard_fields[0] shard_group = getattr(shard_field, 'django_sharding__shard_group', None) if not shard_group: raise Exception( 'The model {} with the shard field must have a `shard_group` attribute' .format(model)) if not getattr(shard_field, 'django_sharding__use_signal', False): continue group_settings = shard_settings.get(shard_group, {}) if group_settings.get('SKIP_ADD_SHARDED_SIGNAL', False): continue receiver(models.signals.pre_save, sender=model)(save_shard_handler)
def event_receiver_decorator(fn): sender = ContentType.objects.get(model=content_type).model_class() dispatch_uid = '%s_%s_%s' % (fn.__name__, content_type, type_) wrapper = receiver(signal, sender=sender, dispatch_uid=dispatch_uid) return wrapper(fn)
# # Register event handlers if rocketchat integration is enabled # def logout_handler(sender, user, request, **kwargs): """ Logout Rocketchat user when receives a Django logout signal. """ # Superuser cannot logout because that would invalidate the Auth token if user and not user.is_superuser: submit(silence_exceptions(rocket.logout), user) def silence_exceptions(func): """ Log errors instead of proagating exceptions. """ # noinspection PyBroadException def wrapped(*args, **kwargs): try: return func(*args, **kwargs) except Exception as exc: msg = f"Error encountered executing {func.__name__}: {exc}" log.error(msg) return wrapped if settings.EJ_ROCKETCHAT_INTEGRATION: receiver(user_logged_out)(logout_handler)
class JobUploadDocument(models.Model): job = models.ForeignKey('employer.Job') document_type = models.ForeignKey('employer.JobUploadDocumentType') document = models.FileField(upload_to="job_document/%Y/%m/%d") def __unicode__(self): if self.document: return self.document.name.split('/')[-1] else: return super(JobUploadDocument, self).__unicode__() def clean(self): max_count = self.document_type.max_count if max_count > 0: if JobUploadDocument.objects.filter(job=self.job, document_type=self.document_type).count() >= max_count: raise ValidationError("Too many Files for category {0}".format(self.document_type.__unicode__())) def after_update(sender, **kwargs): if 'created' not in kwargs or not kwargs['created']: update_index.delay() else: instance = kwargs['instance'] Essential.objects.create(job=instance, essential=' ') Desireable.objects.create(job=instance, desireable=' ') receiver(post_save, sender=Job)(after_update) receiver(post_delete, sender=Job)(after_update) receiver(m2m_changed, sender=Job)(after_update)