def synchronize_extractor_task(sender, *args, **kwargs): pre_init.disconnect(synchronize_extractor_task, sender=sender) doc = sender.__dict__.get('__doc__') if doc.startswith(sender.__name__): keys = doc[len(sender.__name__) + 1:-1].split(', ') values = kwargs.get('args') if len(keys) == len(values): kvp = dict((k, values[i]) for i, k in enumerate(keys)) try: instance = AsyncExtractorTask.objects.get(uuid=kvp['uuid']) except AsyncExtractorTask.DoesNotExist: pass else: if instance.success is None: url = instance.details['possible_requests']['status'][ 'url'] r = requests.get(url) if r.status_code == 200: details = instance.details details.update(r.json()) instance.success = { 'SUCCESS': True, 'FAILURE': False, }.get(details['status'], None) instance.details = details if instance.success is False: instance.stop_datetime = timezone.now() else: instance.stop_datetime = details.get( 'end_datetime') instance.start_datetime = \ details.get('start_datetime') or instance.stop_datetime instance.save() if instance.success is True: send_extraction_successfully_mail( instance.user, instance) elif instance.success is False: send_extraction_failure_mail( instance.user, instance) pre_init.connect(synchronize_extractor_task, sender=sender)
def contribute_to_class(self, cls, name): super(PolymorphicChildManager, self).contribute_to_class(cls, name) polymorphic_on = self._polymorphic_manager.polymorphic_on identity = self._identity id2model = self._polymorphic_manager._id2model if identity in id2model: raise ImproperlyConfigured( 'More than one subclasses with the same identity (%s.%s=%s)' % (self._polymorphic_manager.model.__name__, polymorphic_on, identity)) id2model[identity] = cls if self._autoinit: def preset_identity(sender, args, kwargs, **_): if polymorphic_on not in kwargs: kwargs[polymorphic_on] = identity pre_init.connect(preset_identity, sender=cls, weak=False)
from django.db.models.signals import pre_delete, post_delete from django.db.models.signals import m2m_changed from django.db.models.signals import pre_migrate, post_migrate from django.test.signals import setting_changed from django.test.signals import template_rendered from django.db.backends.signals import connection_created def f1(sender, **kwargs): print("execute ------f1 signal----------") # print(sender, kwargs) pre_init.connect(f1) import django.dispatch custom_signal_name = django.dispatch.Signal(providing_args=["aaa", "bbb"]) # def callback(sender, **kwargs): # print("callback") # print(sender, kwargs) # # # pizza_done.connect(callback)
from django.db.models import Model from django.db.models.signals import class_prepared, pre_init from .utils import normalize_table def transform_db_table(sender: Model, **kwargs): from .settings import db_settings should_transform = (db_settings.ENABLE_TRANSFORM_DB_TABLE and db_settings.DEFAULT_DB_TABLE_PATTERN) if should_transform: normalized_name = normalize_table( sender._meta.db_table, format=db_settings.DEFAULT_DB_TABLE_PATTERN, exclude=db_settings.IGNORE_DB_TABLE_PATTERNS, ) sender._meta.db_table = normalized_name pre_init.connect(transform_db_table) class_prepared.connect(transform_db_table)
from django.db.models.signals import pre_init from courant.core.countthis.models import Statistic from django.contrib.contenttypes.models import ContentType def add_statistics(sender, *args, **kwargs): sender.add_to_class('statistics', lambda self: Statistic.objects.get( content_type= ContentType.objects.get_for_model(self), object_id=self.pk)) pre_init.connect(add_statistics)
from django.conf import settings from django.db.models.signals import class_prepared, pre_init def add_db_prefix(sender, **kwargs): prefix = getattr(settings, "DB_PREFIX", None) if prefix and not sender._meta.db_table.startswith(prefix) and getattr( sender, 'use_db_prefix', True): sender._meta.db_table = prefix + sender._meta.db_table pre_init.connect(add_db_prefix) class_prepared.connect(add_db_prefix)
creator = models.ForeignKey(CustomUser) reply = models.ManyToManyField(Reply) ##ADMIN class PostAdmin(admin.ModelAdmin): list_display = ["creator", "created"] list_filter = ["creator"] class ReplyAdmin(admin.ModelAdmin): list_display = ["creator", "created"] list_filter = ["creator"] admin.site.register(Post, PostAdmin) admin.site.register(Reply, ReplyAdmin) def Post_creado(sender,args, **kwargs): #Cuando el usuario con ID=2 crea un post este se almacena como post del Admin dic=kwargs.__getitem__('kwargs') if dic.get('creator' ) == CustomUser.objects.get(id=2): dic.__setitem__('creator', CustomUser.objects.get(id=1)) pre_init.connect(Post_creado, sender=Post)
if "auto_set_key_name" in kwargs: if sender.kind() in auto_set_key_name_table and "key_name" not in kwargs: fields = auto_set_key_name_table[sender.kind()] items = [] for f in fields: if not hasattr(sender,f): # It is not a property. It is a keyword items.append(f) continue prop = getattr(sender,f) value = kwargs[f] if isinstance(prop,db.ReferenceProperty): if isinstance(value,db.Key): items.append(value.id_or_name()) else: items.append(value.key().id_or_name()) elif isinstance(prop,MLStringProperty): items.append(MLStringProperty.to_key_name(value)) else: items.append(value) key_name = "-".join(items) kwargs["key_name"] = next_key_name(sender,key_name) del kwargs["auto_set_key_name"] pre_init.connect(auto_set_key_name)
for mturk_assignment in assignments: assert mturk_assignment.HITId == self.mturk_id djurk_assignment, _ = Assignment.objects.get_or_create( mturk_id=mturk_assignment.AssignmentId, hit=self) djurk_assignment.update(mturk_assignment, hit=self) if update_all and int(assignments.PageNumber) *\ page_size < int(assignments.TotalNumResults): self.update_assignments(page_number + 1, page_size, update_all) class Meta: verbose_name = "HIT" verbose_name_plural = "HITs" def __unicode__(self): return u"HIT: %s" % self.mturk_id pre_init.connect(init_connection_callback, sender=HIT) class Assignment(models.Model): """An Amazon Mechanical Turk Assignment as a Django Model""" (_SUBMITTED, _APPROVED, _REJECTED) = ("Submitted", "Approved", "Rejected") (SUBMITTED, APPROVED, REJECTED) = ("S", "A", "R") STATUS_CHOICES = ( (SUBMITTED, _SUBMITTED), (APPROVED, _APPROVED), (REJECTED, _REJECTED), ) # Convenience lookup dictionaries for the above lists reverse_status_lookup = dict((v, k) for k, v in STATUS_CHOICES)
djurk_assignment = Assignment.objects.get_or_create( mturk_id=mturk_assignment.AssignmentId, hit=self)[0] djurk_assignment.update(mturk_assignment, hit=self) if update_all and int(assignments.PageNumber) *\ page_size < int(assignments.TotalNumResults): self.update_assignments(page_number + 1, page_size, update_all) class Meta: verbose_name = "HIT" verbose_name_plural = "HITs" def __unicode__(self): return u"HIT: %s" % self.mturk_id pre_init.connect(init_connection_callback, sender=HIT) class Assignment(models.Model): """An Amazon Mechanical Turk Assignment as a Django Model""" (_SUBMITTED, _APPROVED, _REJECTED) = ("Submitted", "Approved", "Rejected") (SUBMITTED, APPROVED, REJECTED) = ("S", "A", "R") STATUS_CHOICES = ( (SUBMITTED, _SUBMITTED), (APPROVED, _APPROVED), (REJECTED, _REJECTED), ) # Convenience lookup dictionaries for the above lists reverse_status_lookup = dict((v, k) for k, v in STATUS_CHOICES)
def ready(self): MyModel = self.get_model('DiscipleTeacher') pre_init.connect(event_handler, sender=MyModel, dispatch_uid='limit_on_number_recruit')
attributes['debit_derniere_soiree_reg'] = attributes['debit_derniere_soiree'] del attributes['debit_derniere_soiree'] if 'debit_initial' in attributes: attributes['debit_initial_reg'] = attributes['debit_initial'] del attributes['debit_initial'] if 'total_depenses_corrige' in attributes: attributes['total_depenses_corrige_reg'] = attributes['total_depenses_corrige'] del attributes['total_depenses_corrige'] if 'recette_billets_vendus' in attributes: attributes['total_recettes'] = attributes['recette_billets_vendus'] del attributes['recette_billets_vendus'] if 'anecdote' in attributes: del attributes['anecdote'] kwargs['kwargs'] = attributes pre_init.connect(pre_init_budget, BudgetSoiree) class Abonnement(models.Model): debut = models.DateField() fin = models.DateField() tarif = models.IntegerField() abonne = models.ForeignKey('Personne') def __unicode__(self): return u'Abonnement du {0.debut!s} au {0.fin!s} pour la somme de {0.montant!s}d'.format(self) # récapitualif "hors compte", non associé à une transaction class Recapitulatif(models.Model): T_RECAPITULATIF = ( (0, 'hebdomadaire'),
templates = [] for extension in request.extension: for template in arguments[0]: if template: templates.append("".join([template, ".", extension])) arguments[0] = templates return render_to_response(*arguments, **kwargs) # Make common_tags available everywhere for library in settings.TEMPLATE_TAGS: add_to_builtins(library) # Add a .type method to every object, so you can ask it what type it is from templates def add_type(sender, *args, **kwargs): sender.add_to_class("type", lambda self: self._meta.verbose_name) pre_init.connect(add_type) # register Tag model with gettag, since Tag model can't be modified directly (svn:external) gettag.register( Tag, name_field="tag__name", with_func=Tag.objects.usage_for_queryset, in_func=TaggedItem.objects.get_by_model ) # register ContentType with gettag gettag.register(ContentType, name_field="model")
@return: """ act = kwargs['instance'] act.acthome = os.path.join(act.venue.VENUE_ROOT, 'acts', act.actname) act.uwsgi_ip = None act.uwsgi_port = None act.uwsgifile = os.path.join(act.acthome, 'uwsgi.ini') if not os.path.exists(act.acthome): print 'Act %s does not exist in venue %s' % (act.venue.VENUE_NAME, act.actname) raise return def postpopulate_act(sender, **kwargs): """ Populate an act instance with some parameters and methods @param sender: @param kwargs: @return: """ act = kwargs['instance'] act.get_settings() act.uwsgi_linker() act.uwsgi_log = act.get_uwsgi_log() return #Execute upon initiation of Venue object. #Populate some content for the venue pre_init.connect(prevalidate_act, sender=Act) post_init.connect(postpopulate_act, sender=Act) pre_init.connect(prevalidate_venue, sender=Venue) post_init.connect(postpopulate_venue, sender=Venue)
def ready(self): pre_init.connect(add_db_prefix) class_prepared.connect(add_db_prefix) logger.info("CONNECTED PREFIX SIGNALS")
from django.core.signals import request_finished from django.core.signals import request_started from django.core.signals import got_request_exception from django.db.models.signals import class_prepared from django.db.models.signals import pre_init, post_init from django.db.models.signals import pre_save, post_save from django.db.models.signals import pre_delete, post_delete from django.db.models.signals import m2m_changed from django.db.models.signals import pre_migrate, post_migrate from django.test.signals import setting_changed from django.test.signals import template_rendered from django.db.backends.signals import connection_created def callback(sender, **kwargs): print("xxoo_callback") print(sender,kwargs) pre_init.connect(callback) #加载pre_init
#!/usr/local/bin/env python3 # -*- coding:utf-8 -*- # __author__:"Howard" from django.core.signals import request_finished from django.core.signals import request_started from django.core.signals import got_request_exception from django.db.models.signals import class_prepared from django.db.models.signals import pre_init, post_init from django.db.models.signals import pre_save, post_save from django.db.models.signals import pre_delete, post_delete from django.db.models.signals import m2m_changed from django.db.models.signals import pre_migrate, post_migrate from django.test.signals import setting_changed from django.test.signals import template_rendered from django.db.backends.signals import connection_created def callback(sender, **kwargs): print("xxoo_callback") print(sender,kwargs) pre_init.connect(callback)
from django.test.signals import setting_changed from django.test.signals import template_rendered from django.db.backends.signals import connection_created # region 注册方式1 # 接受信号函数 def callback(sender, **kwargs): # print("pre_init_callback") # print(sender, kwargs) pass # 注册接受数据库对象构造函数触发信号 pre_init.connect(callback) # endregion # region 注册方式2 from django.core.signals import request_finished from django.dispatch import receiver @receiver(request_finished) def my_callback(sender, **kwargs): # print("Request finished!") pass # endregion
from django.conf import settings from django.db.models.signals import class_prepared, pre_init def add_db_prefix(sender, **kwargs): prefix = getattr(settings, "DB_PREFIX", None) if prefix and not sender._meta.db_table.startswith(prefix): sender._meta.db_table = prefix + sender._meta.db_table pre_init.connect(add_db_prefix) class_prepared.connect(add_db_prefix)