Beispiel #1
0
 def contribute_to_class(self, cls, name):
     super(FileField, self).contribute_to_class(cls, name)
     setattr(cls, 'get_%s_filename' % self.name, curry(cls._get_FIELD_filename, field=self))
     setattr(cls, 'get_%s_url' % self.name, curry(cls._get_FIELD_url, field=self))
     setattr(cls, 'get_%s_size' % self.name, curry(cls._get_FIELD_size, field=self))
     setattr(cls, 'save_%s_file' % self.name, lambda instance, filename, raw_contents, save=True: instance._save_FIELD_file(self, filename, raw_contents, save))
     dispatcher.connect(self.delete_file, signal=signals.post_delete, sender=cls)
Beispiel #2
0
Datei: utils.py Projekt: ewe2/G2
def set_defaults(app, *defaults):
    "Installs a set of default values during syncdb processing"
    from django.core.exceptions import ImproperlyConfigured
    from django.dispatch import dispatcher
    from django.db.models import signals
    from dbsettings.loading import get_setting_storage, set_setting_value

    if not defaults:
        raise ImproperlyConfigured(
            "No defaults were supplied to set_defaults.")
    app_label = app.__name__.split('.')[-2]

    def install_settings(app, created_models, verbosity=2):
        printed = False

        for class_name, attribute_name, value in defaults:
            if not get_setting_storage(app.__name__, class_name,
                                       attribute_name):
                if verbosity >= 2 and not printed:
                    # Print this message only once, and only if applicable
                    print "Installing default settings for %s" % app_label
                    printed = True
                try:
                    set_setting_value(app.__name__, class_name, attribute_name,
                                      value)
                except:
                    raise ImproperlyConfigured("%s requires dbsettings." %
                                               app_label)

    dispatcher.connect(install_settings,
                       sender=app,
                       signal=signals.post_syncdb,
                       weak=False)
def set_defaults(app, *defaults):
    "Installs a set of default values during syncdb processing"
    from django.core.exceptions import ImproperlyConfigured
    from django.dispatch import dispatcher
    from django.db.models import signals
    from dbsettings.loading import get_setting_storage, set_setting_value

    if not defaults:
        raise ImproperlyConfigured("No defaults were supplied to set_defaults.")
    app_label = app.__name__.split('.')[-2]

    def install_settings(app, created_models, verbosity=2):
        printed = False

        for class_name, attribute_name, value in defaults:
            if not get_setting_storage(app.__name__, class_name, attribute_name):
                if verbosity >= 2 and not printed:
                    # Print this message only once, and only if applicable
                    print "Installing default settings for %s" % app_label
                    printed = True
                try:
                    set_setting_value(app.__name__, class_name, attribute_name, value)
                except:
                    raise ImproperlyConfigured("%s requires dbsettings." % app_label)

    dispatcher.connect(install_settings, sender=app, signal=signals.post_syncdb, weak=False)
Beispiel #4
0
 def contribute_to_class(self, cls, name):
     super(FileField, self).contribute_to_class(cls, name)
     setattr(cls, 'get_%s_filename' % self.name, curry(cls._get_FIELD_filename, field=self))
     setattr(cls, 'get_%s_url' % self.name, curry(cls._get_FIELD_url, field=self))
     setattr(cls, 'get_%s_size' % self.name, curry(cls._get_FIELD_size, field=self))
     setattr(cls, 'save_%s_file' % self.name, lambda instance, filename, raw_contents, save=True: instance._save_FIELD_file(self, filename, raw_contents, save))
     dispatcher.connect(self.delete_file, signal=signals.post_delete, sender=cls)
def version_model(model):
    """
    Based on the passed model, build a second model to store versioning information.
    Register functions to write version changes on save and delete of the original model
    NOTE: be sure to use strong references for signal connections so that inner funcs don't get
        garbage collected
    """
    version_model = _build_version_model(model)
    _decorate_model(model,version_model)
            
    def record_change(instance,change_type):
        version_instance = _version_from_instance(instance,version_model)
        version_instance.change_type = change_type  
        version_instance.save()    

    def record_save(sender,instance,signal, *args, **kwargs):
        # Record the save to the shadow table
        record_change(instance,"SAVE")
    dispatcher.connect(record_save,signal=signals.post_save,sender=model,weak=False)
        
    def record_delete(sender,instance,signal,*args,**kwargs):
        # Record the delete to the shadow table
        record_change(instance,"DELETE")      
    dispatcher.connect(record_delete,signal=signals.pre_delete,sender=model,weak=False)     

    setattr(model,'version_model',version_model)

    return version_model
Beispiel #6
0
 def create_or_update(self, instance, timestamp=None, tags="", source="INTERACTIVE", source_id=""):
     """
     Create or update an Item from some instace.
     """
     # If the instance hasn't already been saved, save it first. This
     # requires disconnecting the post-save signal that might be sent to
     # this function (otherwise we could get an infinite loop).
     if instance._get_pk_val() is None:
         try:
             dispatcher.disconnect(self.create_or_update, signal=signals.post_save, sender=type(instance))
         except dispatcher.errors.DispatcherError:
             reconnect = False
         else:
             reconnect = True
         instance.save()
         if reconnect:
             dispatcher.connect(self.create_or_update, signal=signals.post_save, sender=type(instance))
     
     # Make sure the item "should" be registered.
     if not getattr(instance, "jellyrollable", True):
         return
     
     # Check to see if the timestamp is being updated, possibly pulling
     # the timestamp from the instance.
     if hasattr(instance, "timestamp"):
         timestamp = instance.timestamp
     if timestamp is None:
         update_timestamp = False
         timestamp = datetime.datetime.now()
     else:
         update_timestamp = True
                 
     # Ditto for tags.
     if not tags:
         for f in instance._meta.fields:
             if isinstance(f, TagField):
                 tags = getattr(instance, f.attname)
                 break
     
     # Create the Item object.
     ctype = ContentType.objects.get_for_model(instance)
     item, created = self.get_or_create(
         content_type = ctype, 
         object_id = instance._get_pk_val(),
         defaults = dict(
             timestamp = timestamp,
             source = source,
             source_id = source_id,
             tags = tags,
         )
     )        
     item.tags = tags
     item.source = source
     item.source_id = source_id
     if update_timestamp:
         item.timestamp = timestamp
         
     # Save and return the item.
     item.save()
     return item
Beispiel #7
0
 def process_request(self, request):
     self.time_started = time.time()
     self.templates_used = []
     self.contexts_used = []
     self.sql_offset_start = len(connection.queries)
     dispatcher.connect(self._storeRenderedTemplates,
                        signal=template_rendered)
Beispiel #8
0
 def _save(self, instance=None):
     if not self.auto_rename: return
     if instance == None: return
     if not instance._get_pk_val():
         # NEW OBJECT, connect to the post_save for renaming
         dispatcher.connect(self._save_new,
                            signals.post_save,
                            sender=instance)
         return
     image = getattr(instance, self.attname)
     if self.name_field:
         image = rename_by_field(image, '%s-%s-%s' \
                                 % (instance.__class__.__name__,
                                    self.name,
                                    getattr(instance, self.name_field)
                                    )
                                 )
     else:
         # XXX this needs testing, maybe it can generate too long image names (max is 100)
         image = rename_by_field(image, '%s-%s-%s' \
                                 % (instance.__class__.__name__,
                                    self.name,
                                    instance._get_pk_val()
                                    )
                                 )
     setattr(instance, self.attname, image)
    def request(self, **request):
        """
        The master request method. Composes the environment dictionary
        and passes to the handler, returning the result of the handler.
        Assumes defaults for the query environment, which can be overridden
        using the arguments to the request.
        """

        environ = {
            'HTTP_COOKIE':      self.cookies,
            'PATH_INFO':         '/',
            'QUERY_STRING':      '',
            'REQUEST_METHOD':    'GET',
            'SCRIPT_NAME':       None,
            'SERVER_NAME':       'testserver',
            'SERVER_PORT':       80,
            'SERVER_PROTOCOL':   'HTTP/1.1',
        }
        environ.update(self.defaults)
        environ.update(request)

        # Curry a data dictionary into an instance of
        # the template renderer callback function
        data = {}
        on_template_render = curry(store_rendered_templates, data)
        dispatcher.connect(on_template_render, signal=signals.template_rendered)

        # Capture exceptions created by the handler
        dispatcher.connect(self.store_exc_info, signal=got_request_exception)

        response = self.handler(environ)

        # Add any rendered template detail to the response
        # If there was only one template rendered (the most likely case),
        # flatten the list to a single element
        for detail in ('template', 'context'):
            if data.get(detail):
                if len(data[detail]) == 1:
                    setattr(response, detail, data[detail][0]);
                else:
                    setattr(response, detail, data[detail])
            else:
                setattr(response, detail, None)

        # Look for a signalled exception and reraise it
        if self.exc_info:
            raise self.exc_info[1], None, self.exc_info[2]
        
        # Update persistent cookie and session data
        if response.cookies:
            self.cookies.update(response.cookies)

        if 'django.contrib.sessions' in settings.INSTALLED_APPS:
            from django.contrib.sessions.middleware import SessionWrapper
            cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
            if cookie:
                self.session = SessionWrapper(cookie.value)
            
        return response
Beispiel #10
0
    def contribute_to_class(self, cls, name):
        super(TagField, self).contribute_to_class(cls, name)

        # Make this object the descriptor for field access.
        setattr(cls, self.name, self)

        # Save tags back to the database post-save
        dispatcher.connect(self._save, signal=signals.post_save, sender=cls)
Beispiel #11
0
    def contribute_to_class(self, cls, name):
        super(TagField, self).contribute_to_class(cls, name)

        # Make this object the descriptor for field access.
        setattr(cls, self.name, self)

        # Save tags back to the database post-save
        dispatcher.connect(self._save, signal=signals.post_save, sender=cls)
Beispiel #12
0
def register(model, parent_attr='parent', left_attr='lft', right_attr='rght',
             tree_id_attr='tree_id', level_attr='level',
             tree_manager_attr='tree', order_insertion_by=None):
    """
    Sets the given model class up for Modified Preorder Tree Traversal.
    """
    if model in registry:
        raise AlreadyRegistered(_('The model %s has already been registered.') % model.__name__)
    registry.append(model)

    # Add tree options to the model's Options
    opts = model._meta
    opts.parent_attr = parent_attr
    opts.right_attr = right_attr
    opts.left_attr = left_attr
    opts.tree_id_attr = tree_id_attr
    opts.level_attr = level_attr
    opts.tree_manager_attr = tree_manager_attr
    opts.order_insertion_by = order_insertion_by
    opts.get_field(left_attr).null = True
    opts.get_field(left_attr).blank = True



    # Add tree fields if they do not exist
    for attr in [left_attr, right_attr, tree_id_attr, level_attr]:
        try:
            opts.get_field(attr)
        except FieldDoesNotExist:
            PositiveIntegerField(
                db_index=True, editable=False).contribute_to_class(model, attr)

    # Add tree methods for model instances
    setattr(model, 'get_ancestors', models.get_ancestors)
    setattr(model, 'get_children', models.get_children)
    setattr(model, 'get_descendants', models.get_descendants)
    setattr(model, 'get_descendant_count', models.get_descendant_count)
    setattr(model, 'get_next_sibling', models.get_next_sibling)
    setattr(model, 'get_previous_sibling', models.get_previous_sibling)
    setattr(model, 'get_root', models.get_root)
    setattr(model, 'get_siblings', models.get_siblings)
    setattr(model, 'insert_at', models.insert_at)
    setattr(model, 'is_child_node', models.is_child_node)
    setattr(model, 'is_leaf_node', models.is_leaf_node)
    setattr(model, 'is_root_node', models.is_root_node)
    setattr(model, 'move_to', models.move_to)

    # Add a custom tree manager
    TreeManager(parent_attr, left_attr, right_attr, tree_id_attr,
                level_attr).contribute_to_class(model, tree_manager_attr)
    setattr(model, '_tree_manager', getattr(model, tree_manager_attr))

    # Set up signal receivers to manage the tree when instances of the
    # model are about to be created, have their parent changed or be
    # deleted.
    dispatcher.connect(pre_save, signal=model_signals.pre_save, sender=model)
    dispatcher.connect(pre_delete, signal=model_signals.pre_delete, sender=model)
 def connect(self):
     """
     Hooks up the moderation methods to pre- and post-save signals
     from the comment models.
     
     """
     for model in (Comment, FreeComment):
         dispatcher.connect(self.pre_save_moderation, sender=model, signal=signals.pre_save)
         dispatcher.connect(self.post_save_moderation, sender=model, signal=signals.post_save)
Beispiel #14
0
 def contribute_to_class(self, cls, name):
     super(JSONField, self).contribute_to_class(cls, name)
     dispatcher.connect(self.post_init, signal=signals.post_init, sender=cls)
     
     def get_json(model_instance):
         return dumps(getattr(model_instance, self.attname, None))
     setattr(cls, 'get_%s_json' % self.name, get_json)
 
     def set_json(model_instance, json):
         return setattr(model_instance, self.attname, loads(json))
     setattr(cls, 'set_%s_json' % self.name, set_json)
Beispiel #15
0
 def contribute_to_class(self, cls, name):
     super(JSONField, self).contribute_to_class(cls, name)
     dispatcher.connect(self.post_init, signal=signals.post_init, sender=cls)
     
     def get_json(model_instance):
         return dumps(getattr(model_instance, self.attname, None))
     setattr(cls, 'get_%s_json' % self.name, get_json)
 
     def set_json(model_instance, json):
         return setattr(model_instance, self.attname, loads(json))
     setattr(cls, 'set_%s_json' % self.name, set_json)
    def contribute_to_class(self, cls, name):
        # Make sure the fields exist (these raise FieldDoesNotExist,
        # which is a fine error to raise here)
        self.name = name
        self.model = cls
        self.cache_attr = "_%s_cache" % name

        # For some reason I don't totally understand, using weakrefs here doesn't work.
        dispatcher.connect(self.instance_pre_init, signal=signals.pre_init, sender=cls, weak=False)

        # Connect myself as the descriptor for this field
        setattr(cls, name, self)
Beispiel #17
0
    def contribute_to_class(self, cls, name):
        # Make sure the fields exist (these raise FieldDoesNotExist,
        # which is a fine error to raise here)
        self.name = name
        self.model = cls
        self.cache_attr = "_%s_cache" % name

        # For some reason I don't totally understand, using weakrefs here doesn't work.
        dispatcher.connect(self.instance_pre_init, signal=signals.pre_init, sender=cls, weak=False)

        # Connect myself as the descriptor for this field
        setattr(cls, name, self)
Beispiel #18
0
    def contribute_to_class(cls, main_cls, name):
        """
        Handle the inner 'Translation' class.
        """

        # delay the creation of the *Translation until the master model is
        # fully created
        connect(cls.finish_multilingual_class, signal=signals.class_prepared,
                sender=main_cls, weak=False)
    
        # connect the post_save signal on master class to a handler
        # that saves translations
        connect(translation_save_translated_fields, signal=signals.post_save,
                sender=main_cls)
Beispiel #19
0
 def post_article_comment_save(sender,instance):
     if instance.content_type == ContentType.objects.get_for_model(Article):
        ym=instance.get_content_object()
        from django.core.mail import send_mail
        from django.template import Context, loader
        subject = 'New Comment by %s on %s'%(instance.user.username,ym.title)
        message_template = loader.get_template('comment_notification_email.txt')
        message_context = Context({ 'comment':instance,"content_object":ym})
        message = message_template.render(message_context)
        send_mail(subject, message,settings.DEFAULT_FROM_EMAIL,[ym.user.email])
        
        dispatcher.connect(
        post_article_comment_save, sender=Comment,signal=models.signals.post_save
        )
    def contribute_to_class(self, cls, name):
        super(S3FileField, self).contribute_to_class(cls, name)
        models.CharField(maxlength=200, blank=self.blank, null=self.null).contribute_to_class(cls, "%s_key"%(self.name))
        models.CharField(maxlength=200, blank=self.blank, null=self.null, default=(self.bucket or settings.DEFAULT_BUCKET)).contribute_to_class(cls, "%s_bucket"%(self.name))
        models.CharField(maxlength=200, blank=True, null=True, default="").contribute_to_class(cls, "%s_content_type"%(self.name))
        models.IntegerField(blank=True, null=True).contribute_to_class(cls, "%s_size"%(self.name))
        if self.is_image:
            models.IntegerField(blank=True, null=True).contribute_to_class(cls, "%s_width"%(self.name))
            models.IntegerField(blank=True, null=True).contribute_to_class(cls, "%s_height"%(self.name))

        # Getter for the file url
        def get_url(instance, field):
            return field.get_url(instance)
        setattr(cls, 'get_%s_url' % self.name, curry(get_url, field=self))

        dispatcher.connect(self.delete_file, signal=signals.post_delete, sender=cls)
Beispiel #21
0
    def finish_multilingual_class(cls, *args, **kwargs):
        """
        Create a model with translations of a multilingual class.
        """

        main_cls = kwargs['sender']
        translation_model_name = main_cls.__name__ + "Translation"

        # create the model with all the translatable fields
        class TransMeta:
            ordering = ('language_id',)
            unique_together = (('master', 'language_id'),)
            db_table = main_cls._meta.db_table + 'translation'
            app_label = main_cls._meta.app_label
    
        trans_attrs = cls.__dict__.copy()
        trans_attrs['Meta'] = TransMeta
        trans_attrs['language_id'] = models.IntegerField(blank=False, null=False, core=True,
                                                         choices=get_language_choices(),
                                                         db_index=True)
        trans_attrs['master'] = TranslationForeignKey(main_cls, blank=False, null=False,
                                                      edit_inline=TransBoundRelatedObject,
                                                      related_name='translations',
                                                      num_in_admin=get_language_count(),
                                                      min_num_in_admin=get_language_count(),
                                                      num_extra_on_change=0)
        trans_attrs['__str__'] = lambda self: ("%s object, language_code=%s"
                                               % (translation_model_name,
                                                  get_language_code(self.language_id)))
    
        trans_model = ModelBase(translation_model_name, (models.Model,), trans_attrs)
        trans_model._meta.translated_fields = cls.create_translation_attrs(main_cls)
    
        main_cls._meta.translation_model = trans_model
        main_cls.get_translation = get_translation
        main_cls.fill_translation_cache = fill_translation_cache

        # Note: don't fill the translation cache in post_init, as all
        # the extra values selected by QAddTranslationData will be
        # assigned AFTER init()
#        connect(fill_translation_cache, signal=signals.post_init,
#                sender=main_cls)

        # connect the pre_save signal on translation class to a
        # function removing previous translation entries.
        connect(translation_overwrite_previous, signal=signals.pre_save,
                sender=trans_model, weak=False)
Beispiel #22
0
def register_custom_permissions(permissions, sender):
    def mk_permissions(permissions, app, verbosity):
        # retrieve actual appname string from module instance
        appname = app.__name__.lower().split('.')[-2]
        # create a content type for the app
        ct, created = ContentType.objects.get_or_create(model='', app_label=appname,
            defaults={'name': appname})
        if created and verbosity >= 2: print "Adding custom content type '%s'" % ct
        # create permissions
        for codename, name in permissions:
            p, created = Permission.objects.get_or_create(codename=codename,
                content_type__pk=ct.id,
                defaults={'name': name, 'content_type': ct})
            if created and verbosity >= 2:
                print "Adding custom permission '%s'" % p

    dispatcher.connect(lambda app, verbosity: mk_permissions(permissions, app, verbosity),
        sender=sender, signal=signals.post_syncdb, weak=False)
Beispiel #23
0
def register_custom_permissions(permissions, sender):
    def mk_permissions(permissions, app, verbosity):
        # retrieve actual appname string from module instance
        appname = app.__name__.lower().split('.')[-2]
        # create a content type for the app
        ct, created = ContentType.objects.get_or_create(model='', app_label=appname,
                                                        defaults={'name': appname})
        if created and verbosity >= 2: print "Adding custom content type '%s'" % ct
        # create permissions
        for codename, name in permissions:
            p, created = Permission.objects.get_or_create(codename=codename,
                                                          content_type__pk=ct.id,
                                                          defaults={'name': name, 'content_type': ct})
            if created and verbosity >= 2:
                print "Adding custom permission '%s'" % p

    dispatcher.connect(lambda app, verbosity: mk_permissions(permissions, app, verbosity),
                       sender=sender, signal=signals.post_syncdb, weak=False)
Beispiel #24
0
 def _save(self, instance=None):
     if not self.auto_rename: return
     if instance == None: return
     if not instance._get_pk_val():
         # NEW OBJECT, connect to the post_save for renaming
         dispatcher.connect(self._save_new, signals.post_save, sender=instance)
         return
     image = getattr(instance, self.attname)
     if self.name_field:
         image = rename_by_field(image, '%s-%s-%s' \
                                 % (instance.__class__.__name__,
                                    self.name,
                                    getattr(instance, self.name_field)
                                    )
                                 )
     else:
         # XXX this needs testing, maybe it can generate too long image names (max is 100)
         image = rename_by_field(image, '%s-%s-%s' \
                                 % (instance.__class__.__name__,
                                    self.name,
                                    instance._get_pk_val()
                                    )
                                 )
     setattr(instance, self.attname, image)
    def request(self, **request):
        """
        The master request method. Composes the environment dictionary
        and passes to the handler, returning the result of the handler.
        Assumes defaults for the query environment, which can be overridden
        using the arguments to the request.
        """
        environ = {
            'HTTP_COOKIE':      self.cookies,
            'PATH_INFO':         '/',
            'QUERY_STRING':      '',
            'REQUEST_METHOD':    'GET',
            'SCRIPT_NAME':       '',
            'SERVER_NAME':       'testserver',
            'SERVER_PORT':       80,
            'SERVER_PROTOCOL':   'HTTP/1.1',
        }
        environ.update(self.defaults)
        environ.update(request)

        # Curry a data dictionary into an instance of the template renderer
        # callback function.
        data = {}
        on_template_render = curry(store_rendered_templates, data)
        dispatcher.connect(on_template_render, signal=signals.template_rendered)

        # Capture exceptions created by the handler.
        dispatcher.connect(self.store_exc_info, signal=got_request_exception)

        try:
            response = self.handler(environ)
        except TemplateDoesNotExist as e:
            # If the view raises an exception, Django will attempt to show
            # the 500.html template. If that template is not available,
            # we should ignore the error in favor of re-raising the
            # underlying exception that caused the 500 error. Any other
            # template found to be missing during view error handling
            # should be reported as-is.
            if e.args != ('500.html',):
                raise

        # Look for a signalled exception, clear the current context
        # exception data, then re-raise the signalled exception.
        # Also make sure that the signalled exception is cleared from
        # the local cache!
        if self.exc_info:
            exc_info = self.exc_info
            self.exc_info = None
            raise exc_info[1].with_traceback(exc_info[2])

        # Save the client and request that stimulated the response.
        response.client = self
        response.request = request

        # Add any rendered template detail to the response.
        # If there was only one template rendered (the most likely case),
        # flatten the list to a single element.
        for detail in ('template', 'context'):
            if data.get(detail):
                if len(data[detail]) == 1:
                    setattr(response, detail, data[detail][0]);
                else:
                    setattr(response, detail, data[detail])
            else:
                setattr(response, detail, None)

        # Update persistent cookie data.
        if response.cookies:
            self.cookies.update(response.cookies)

        return response
Beispiel #26
0
"""
Creates the default Site object.
"""

from django.dispatch import dispatcher
from django.db.models import signals
from django.contrib.sites.models import Site
from django.contrib.sites import models as site_app


def create_default_site(app, created_models, verbosity):
    if Site in created_models:
        if verbosity >= 2:
            print("Creating example.com Site object")
        s = Site(domain="example.com", name="example.com")
        s.save()
    Site.objects.clear_cache()


dispatcher.connect(create_default_site,
                   sender=site_app,
                   signal=signals.post_syncdb)
Beispiel #27
0

# SIGNALS AND LISTENERS
from django.db.models import signals


# Show
def show_pre_save(sender, instance, signal, *args, **kwargs):
    instance.slug = slugify(instance.name)
    instance.group = slugify(instance.group)


if signals_refactored:
    signals.pre_save.connect(show_pre_save, sender=Show)
else:
    dispatcher.connect(show_pre_save, signal=signals.pre_save, sender=Show)


# CreditsLog
def creditslog_post_save(sender, instance, signal, *args, **kwargs):
    if not instance.saved_to_ad:
        instance.ad.view_credits += instance.view_credits
        instance.ad.click_credits += instance.click_credits
        instance.ad.save()

        instance.saved_to_ad = True
        instance.save()


if signals_refactored:
    signals.post_save.connect(creditslog_post_save, sender=CreditsLog)
GET_ITERATOR_CHUNK_SIZE = 100


def ensure_default_manager(sender):
    cls = sender
    if not hasattr(cls, '_default_manager'):
        # Create the default manager, if needed.
        try:
            cls._meta.get_field('objects')
            raise ValueError, "Model %s must specify a custom Manager, because it has a field named 'objects'" % cls.__name__
        except FieldDoesNotExist:
            pass
        cls.add_to_class('objects', Manager())


dispatcher.connect(ensure_default_manager, signal=signals.class_prepared)


class Manager(object):
    # Tracks each time a Manager instance is created. Used to retain order.
    creation_counter = 0

    def __init__(self):
        super(Manager, self).__init__()
        # Increase the creation counter, and save our local copy.
        self.creation_counter = Manager.creation_counter
        Manager.creation_counter += 1
        self.model = None

    def contribute_to_class(self, model, name):
        # TODO: Use weakref because of possible memory leak / circular reference.
Beispiel #29
0
        cache = CacheState(hash=hash)
        get_avatar(cache, site, email)

    try:
        cache.save()
        if cache.enabled:
            return (urlparse.urljoin(settings.MEDIA_URL, os.path.join(AVATARS_CACHE_DIR, hash + '.png')),
                    dict(width = cache.actual_width, height = cache.actual_height))
    except Exception:
        logger.exception("can't save avatar cache")
    return (None, dict(width=0, height=0))

def comment_postsave(sender, instance):
    hash = gen_hash(instance.author_email, instance.author_site)
    try:
        cache = CacheState.objects.get(hash=hash)
        cache.expire_after = datetime.datetime.today()
        cache.save()
    except CacheState.DoesNotExist:
        pass

if __name__ == 'avatars.models':
    from django.dispatch import dispatcher
    from django.db.models import signals
    try:
        from lfcomments.models import Comment
        dispatcher.connect(comment_postsave, signal=signals.post_save, sender=Comment)
    except Exception, e:
        logging.warning('post_save hook was disabled because of exception: %s' % e)

Beispiel #30
0
    height = models.PositiveIntegerField()

    def get_url(self):
        return '/images/db/' + self.path

    def get_path(self, create=False):
        full_path = os.path.join(settings.CIA_DATA_PATH, 'db', 'images' , self.path)
        if create:
            directory = os.path.dirname(full_path)
            try:
                os.makedirs(directory)
            except OSError:
                pass
        return full_path

    def update_image_size(self):
        self.width, self.height = ImageInstance.objects.magick.get_image_size(self.get_path())

    def to_html(self):
        return '<img src="%s" width="%d" height="%d" />' % (
            self.get_url(), self.width, self.height)

def remove_deleted_instance(instance):
    if instance.delete_file:
        try:
            os.unlink(instance.get_path())
        except OSError:
            pass

dispatcher.connect(remove_deleted_instance, signal=signals.post_delete, sender=ImageInstance)

def create_superuser(app, created_models, verbosity, **kwargs):
    from django.contrib.auth.models import User
    from django.core.management import call_command
    if User in created_models and kwargs.get('interactive', True):
        msg = "\nYou just installed Django's auth system, which means you don't have " \
                "any superusers defined.\nWould you like to create one now? (yes/no): "
        confirm = raw_input(msg)
        while 1:
            if confirm not in ('yes', 'no'):
                confirm = raw_input('Please enter either "yes" or "no": ')
                continue
            if confirm == 'yes':
                call_command("createsuperuser", interactive=True)
            break


if 'create_permissions' not in [
        i.__name__
        for i in dispatcher.getAllReceivers(signal=signals.post_syncdb)
]:
    dispatcher.connect(create_permissions, signal=signals.post_syncdb)
if 'create_superuser' not in [
        i.__name__
        for i in dispatcher.getAllReceivers(signal=signals.post_syncdb,
                                            sender=auth_app)
]:
    dispatcher.connect(create_superuser,
                       sender=auth_app,
                       signal=signals.post_syncdb)
Beispiel #32
0
    class Admin:
        list_display = ('type',)

    class Meta:
        verbose_name_plural = "Element Categories"

    def __str__(self):
        return self.type

# ------------------------------------------------------------------------------
# monkey patched model methods
# ------------------------------------------------------------------------------
Render.getRender = GetRender(Render)
Shot.getShot = GetShot(Shot)
User.getUser = GetUser(User)
Event.getEvent = GetEvent(Event)
Project.getProject = GetProject(Project)

# ------------------------------------------------------------------------------
# signal handler processing
# ------------------------------------------------------------------------------
h = Handler()
dispatcher.connect(h.handle_post_init,  signal=signals.post_init)
dispatcher.connect(h.handle_pre_save,   signal=signals.pre_save)
dispatcher.connect(h.handle_post_save,  signal=signals.post_save)
dispatcher.connect(h.handle_pre_delete, signal=signals.pre_delete)

def getHandler():
    return h
Beispiel #33
0
from django.dispatch import dispatcher
from django.db.models.signals import post_save

from snapshots.models import Snapshot
from snapshots.signals import generate_image


dispatcher.connect(generate_image, signal=post_save, sender=Snapshot)
            ct = ContentType.objects.get(app_label=opts.app_label,
                                         model=opts.object_name.lower())
            content_types.remove(ct)
        except ContentType.DoesNotExist:
            ct = ContentType(name=smart_unicode(opts.verbose_name_raw),
                             app_label=opts.app_label,
                             model=opts.object_name.lower())
            ct.save()
            if verbosity >= 2:
                print "Adding content type '%s | %s'" % (ct.app_label,
                                                         ct.model)
    # The presence of any remaining content types means the supplied app has an
    # undefined model and can safely be removed, which cascades to also remove
    # related permissions.
    for ct in content_types:
        if verbosity >= 2:
            print "Deleting stale content type '%s | %s'" % (ct.app_label,
                                                             ct.model)
        ct.delete()


def update_all_contenttypes(verbosity=2):
    for app in get_apps():
        update_contenttypes(app, None, verbosity)


dispatcher.connect(update_contenttypes, signal=signals.post_syncdb)

if __name__ == "__main__":
    update_all_contenttypes()
Beispiel #35
0
    location            = models.CharField(max_length=50, blank=True, null=True)
    name                = models.CharField(max_length=50, blank=True, null=True)
    thumbnail_url       = models.URLField()
    url                 = models.URLField(blank=True, null=True)
    friends             = models.ManyToManyField('TwitterUser', related_name='friends_user_set', blank=True, null=True)
    followers           = models.ManyToManyField('TwitterUser', related_name='followers_user_set', blank=True, null=True)
    
    def numFriends(self):
        return self.friends.count()
    
    def numFollowers(self):
        return self.followers.count()
    
    def __unicode__(self):
        return self.screen_name
    
    class Admin:
        list_display = ('screen_name', 'name', 'location', 'numFriends', 'numFollowers')


class TweetModerator(CommentModerator):
    akismet = settings.COMMENTS_AKISMET
    auto_moderate_field = 'pub_time'
    moderate_after = settings.COMMENTS_MODERATE_AFTER
    email_notification = settings.COMMENTS_EMAIL
    enable_field = settings.COMMENTS_ENABLE_FIELD
moderator.register(Tweet, TweetModerator)

dispatcher.connect(create_tumblelog_item, sender=Tweet, signal=signals.post_save)
dispatcher.connect(kill_tumblelog_item, sender=Tweet, signal=signals.post_delete)
Beispiel #36
0
 def contribute_to_class(self, cls, name):
     super(ImageWithThumbnailField, self).contribute_to_class(cls, name)
     dispatcher.connect(_delete, signals.post_delete, sender=cls)
     dispatcher.connect(self._save, signals.pre_save, sender=cls)
Beispiel #37
0
    if not app_models:
        return
    for klass in app_models:
        opts = klass._meta
        try:
            ct = ContentType.objects.get(app_label=opts.app_label,
                                         model=opts.object_name.lower())
            content_types.remove(ct)
        except ContentType.DoesNotExist:
            ct = ContentType(name=smart_unicode(opts.verbose_name_raw),
                app_label=opts.app_label, model=opts.object_name.lower())
            ct.save()
            if verbosity >= 2:
                print "Adding content type '%s | %s'" % (ct.app_label, ct.model)
    # The presence of any remaining content types means the supplied app has an
    # undefined model and can safely be removed, which cascades to also remove
    # related permissions.
    for ct in content_types:
        if verbosity >= 2:
            print "Deleting stale content type '%s | %s'" % (ct.app_label, ct.model)
        ct.delete()

def update_all_contenttypes(verbosity=2):
    for app in get_apps():
        update_contenttypes(app, None, verbosity)

dispatcher.connect(update_contenttypes, signal=signals.post_syncdb)

if __name__ == "__main__":
    update_all_contenttypes()
Beispiel #38
0
# Create your models here.
# Place an otherwise blank app in settings.INSTALLED_APPS
# and add the following into the app's models.py:

from django.db.models import signals
from django.dispatch import dispatcher
from django.contrib.auth import models as auth_app
import new, crypt, random, string
from django.utils.encoding import smart_str

def set_password_crypt(self, raw_password):
    algo = 'crypt'
    saltchars = string.ascii_letters + string.digits + './'
    salt = ''.join(random.choice(saltchars) for i in range(2))
    hsh = crypt.crypt(smart_str(raw_password), salt)
    self.password = '******' % (algo, salt, hsh)

def replace_set_password(instance=None):
    instance.set_password = new.instancemethod(
        set_password_crypt, instance, instance.__class__)

dispatcher.connect(replace_set_password,
                   sender=auth_app.User,
                   signal=signals.post_init)
Beispiel #39
0
        elif self.book.textformat == 'markdown':
            import markdown
            self.html = markdown.markdown(self.content)
        super(Chapter, self).save()


def post_save_chapter(sender, instance, signal, *args, **kwargs):
    try:
        book = Book.objects.get(id=instance.book.id)
    except Book.DoesNotExist:
        return


#    book.modifydate = datetime.datetime.now()
    book.save()
dispatcher.connect(post_save_chapter, signal=signals.post_save, sender=Chapter)


class CommentInfo(models.Model):
    chapter = models.ForeignKey(Chapter)
    comment_num = models.CharField(maxlength=20)
    count = models.IntegerField(default=0)


C_STATUS = ((0, 'None'), (1, 'Good'), (2, 'Bad'))


class Comment(models.Model):
    book = models.ForeignKey(Book)
    chapter = models.ForeignKey(Chapter)
    comment_num = models.CharField(maxlength=20)
Beispiel #40
0
        ordering = [
            'id',
        ]

    def save(self):
        if not self.id:
            self.date = datetime.now()
        super(EventFile, self).save()


def add_user_call_back(signal, sender, instance, **kwags):
    """
    >>> from django.contrib.auth.models import User
    >>> u = User.objects.create_user('testuser', '*****@*****.**', password='******')
    >>> profile = u.get_profile()
    >>> profile.nickname
    u'testuser'
    """
    try:
        instance.get_profile()
    except EventProfile.DoesNotExist:
        profile = EventProfile()
        profile.user = instance
        profile.nickname = instance.username
        profile.save()


dispatcher.connect(receiver=add_user_call_back,
                   signal=signals.post_save,
                   sender=User)
Beispiel #41
0
        self.conn.start()
        self.conn.connect()

    def disconnect(self):
        self.conn.stop()


CACHE_DELETER = CacheDeleter()

if AMQ_HOST:
    try:
        import stomp
        import socket

        # check connection to defined AMQ
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((AMQ_HOST, AMQ_PORT))
        s.close()

        # connection checked, connect CACHE_DELETER
        CACHE_DELETER.connect([(AMQ_HOST, AMQ_PORT)])

        # start listening for any model
        dispatcher.connect(CACHE_DELETER.propagate_signal,
                           signal=signals.post_save)
        dispatcher.connect(CACHE_DELETER.propagate_signal,
                           signal=signals.post_delete)
        log.debug('Start listening for any model')
    except:
        log.warning('ActiveMQ not running')
Beispiel #42
0
from django.dispatch import dispatcher
from django.db.models import signals
from django.db.models.fields import FieldDoesNotExist

def ensure_default_manager(sender):
    cls = sender
    if not hasattr(cls, '_default_manager'):
        # Create the default manager, if needed.
        try:
            cls._meta.get_field('objects')
            raise ValueError, "Model %s must specify a custom Manager, because it has a field named 'objects'" % cls.__name__
        except FieldDoesNotExist:
            pass
        cls.add_to_class('objects', Manager())

dispatcher.connect(ensure_default_manager, signal=signals.class_prepared)

class Manager(object):
    # Tracks each time a Manager instance is created. Used to retain order.
    creation_counter = 0

    def __init__(self):
        super(Manager, self).__init__()
        # Increase the creation counter, and save our local copy.
        self.creation_counter = Manager.creation_counter
        Manager.creation_counter += 1
        self.model = None

    def contribute_to_class(self, model, name):
        # TODO: Use weakref because of possible memory leak / circular reference.
        self.model = model
Beispiel #43
0
"""
Copied over from django.contrib.auth.management
"""
from django.dispatch import dispatcher
from django.db.models import get_models, signals

def _get_permission_codename(action, opts):
    return u'%s_%s' % (action, opts.object_name.lower())

def _get_all_permissions(opts):
    "Returns (codename, name) for all permissions in the given opts."
    return [ (_get_permission_codename('view', opts), u'Can view %s' % (opts.verbose_name_raw)), ]

def create_permissions(app, created_models, verbosity):
    from django.contrib.contenttypes.models import ContentType
    from django.contrib.auth.models import Permission
    app_models = get_models(app)
    if not app_models:
        return
    for klass in app_models:
        ctype = ContentType.objects.get_for_model(klass)
        for codename, name in _get_all_permissions(klass._meta):
            p, created = Permission.objects.get_or_create(codename=codename, content_type__pk=ctype.id,
                defaults={'name': name, 'content_type': ctype})
            if created and verbosity >= 2:
                print "Adding permission '%s'" % p

dispatcher.connect(create_permissions, signal=signals.post_syncdb)

        ctype = ContentType.objects.get_for_model(klass)
        for codename, name in _get_all_permissions(klass._meta):
            p, created = Permission.objects.get_or_create(
                codename=codename, content_type__pk=ctype.id, defaults={"name": name, "content_type": ctype}
            )
            if created and verbosity >= 2:
                print "Adding permission '%s'" % p


def create_superuser(app, created_models, verbosity, **kwargs):
    from django.contrib.auth.models import User
    from django.contrib.auth.create_superuser import createsuperuser as do_create

    if User in created_models and kwargs.get("interactive", True):
        msg = (
            "\nYou just installed Django's auth system, which means you don't have "
            "any superusers defined.\nWould you like to create one now? (yes/no): "
        )
        confirm = raw_input(msg)
        while 1:
            if confirm not in ("yes", "no"):
                confirm = raw_input('Please enter either "yes" or "no": ')
                continue
            if confirm == "yes":
                do_create()
            break


dispatcher.connect(create_permissions, signal=signals.post_syncdb)
dispatcher.connect(create_superuser, sender=auth_app, signal=signals.post_syncdb)
Beispiel #45
0
        field.do_related_class(model, cls)
    else:
        key = (app_label, model_name)
        value = (cls, field)
        pending_lookups.setdefault(key, []).append(value)

def do_pending_lookups(sender):
    """
    Handle any pending relations to the sending model. Sent from class_prepared.
    """
    key = (sender._meta.app_label, sender.__name__)
    for cls, field in pending_lookups.pop(key, []):
        field.rel.to = sender
        field.do_related_class(sender, cls)

dispatcher.connect(do_pending_lookups, signal=signals.class_prepared)

def manipulator_valid_rel_key(f, self, field_data, all_data):
    "Validates that the value is a valid foreign key"
    klass = f.rel.to
    try:
        klass._default_manager.get(**{f.rel.field_name: field_data})
    except klass.DoesNotExist:
        raise validators.ValidationError, _("Please enter a valid %s.") % f.verbose_name

#HACK
class RelatedField(object):
    def contribute_to_class(self, cls, name):
        sup = super(RelatedField, self)

        # Add an accessor to allow easy determination of the related query path for this field
Beispiel #46
0
"""
Creates the default Site object.
"""

from django.dispatch import dispatcher
from django.db.models import signals
from django.contrib.sites.models import Site
from django.contrib.sites import models as site_app

def create_default_site(app, created_models, verbosity):
    if Site in created_models:
        if verbosity >= 2:
            print "Creating example.com Site object"
        s = Site(domain="example.com", name="example.com")
        s.save()

dispatcher.connect(create_default_site, sender=site_app, signal=signals.post_syncdb)
Beispiel #47
0
from django import oldforms
from django.core import validators
from django.db.models.fields import FileField, AutoField
from django.dispatch import dispatcher
from django.db.models import signals
from django.utils.functional import curry
from django.utils.datastructures import DotExpandedDict
from django.utils.text import capfirst
import types

def add_manipulators(sender):
    cls = sender
    cls.add_to_class('AddManipulator', AutomaticAddManipulator)
    cls.add_to_class('ChangeManipulator', AutomaticChangeManipulator)

dispatcher.connect(add_manipulators, signal=signals.class_prepared)

class ManipulatorDescriptor(object):
    # This class provides the functionality that makes the default model
    # manipulators (AddManipulator and ChangeManipulator) available via the
    # model class.
    def __init__(self, name, base):
        self.man = None # Cache of the manipulator class.
        self.name = name
        self.base = base

    def __get__(self, instance, model=None):
        if instance != None:
            raise AttributeError, "Manipulator cannot be accessed via instance"
        else:
            if not self.man:
Beispiel #48
0
def register(model,
             parent_attr='parent',
             left_attr='lft',
             right_attr='rght',
             tree_id_attr='tree_id',
             level_attr='level',
             tree_manager_attr='tree',
             order_insertion_by=None):
    """
    Sets the given model class up for Modified Preorder Tree Traversal.
    """
    if model in registry:
        raise AlreadyRegistered(
            _('The model %s has already been registered.') % model.__name__)
    registry.append(model)

    # Add tree options to the model's Options
    opts = model._meta
    opts.parent_attr = parent_attr
    opts.right_attr = right_attr
    opts.left_attr = left_attr
    opts.tree_id_attr = tree_id_attr
    opts.level_attr = level_attr
    opts.tree_manager_attr = tree_manager_attr
    opts.order_insertion_by = order_insertion_by
    opts.get_field(left_attr).null = True
    opts.get_field(left_attr).blank = True

    # Add tree fields if they do not exist
    for attr in [left_attr, right_attr, tree_id_attr, level_attr]:
        try:
            opts.get_field(attr)
        except FieldDoesNotExist:
            PositiveIntegerField(db_index=True,
                                 editable=False).contribute_to_class(
                                     model, attr)

    # Add tree methods for model instances
    setattr(model, 'get_ancestors', models.get_ancestors)
    setattr(model, 'get_children', models.get_children)
    setattr(model, 'get_descendants', models.get_descendants)
    setattr(model, 'get_descendant_count', models.get_descendant_count)
    setattr(model, 'get_next_sibling', models.get_next_sibling)
    setattr(model, 'get_previous_sibling', models.get_previous_sibling)
    setattr(model, 'get_root', models.get_root)
    setattr(model, 'get_siblings', models.get_siblings)
    setattr(model, 'insert_at', models.insert_at)
    setattr(model, 'is_child_node', models.is_child_node)
    setattr(model, 'is_leaf_node', models.is_leaf_node)
    setattr(model, 'is_root_node', models.is_root_node)
    setattr(model, 'move_to', models.move_to)

    # Add a custom tree manager
    TreeManager(parent_attr, left_attr, right_attr, tree_id_attr,
                level_attr).contribute_to_class(model, tree_manager_attr)
    setattr(model, '_tree_manager', getattr(model, tree_manager_attr))

    # Set up signal receivers to manage the tree when instances of the
    # model are about to be created, have their parent changed or be
    # deleted.
    dispatcher.connect(pre_save, signal=model_signals.pre_save, sender=model)
    dispatcher.connect(pre_delete,
                       signal=model_signals.pre_delete,
                       sender=model)
Beispiel #49
0
            return (urlparse.urljoin(
                settings.MEDIA_URL,
                os.path.join(AVATARS_CACHE_DIR, hash + '.png')),
                    dict(width=cache.actual_width, height=cache.actual_height))
    except Exception:
        logger.exception("can't save avatar cache")
    return (None, dict(width=0, height=0))


def comment_postsave(sender, instance):
    hash = gen_hash(instance.author_email, instance.author_site)
    try:
        cache = CacheState.objects.get(hash=hash)
        cache.expire_after = datetime.datetime.today()
        cache.save()
    except CacheState.DoesNotExist:
        pass


if __name__ == 'avatars.models':
    from django.dispatch import dispatcher
    from django.db.models import signals
    try:
        from lfcomments.models import Comment
        dispatcher.connect(comment_postsave,
                           signal=signals.post_save,
                           sender=Comment)
    except Exception, e:
        logging.warning(
            'post_save hook was disabled because of exception: %s' % e)
Beispiel #50
0
get_introspection_module = lambda: __import__(
    'django.db.backends.%s.introspection' % settings.DATABASE_ENGINE, {}, {},
    [''])
get_creation_module = lambda: __import__(
    'django.db.backends.%s.creation' % settings.DATABASE_ENGINE, {}, {}, [''])
runshell = lambda: __import__(
    'django.db.backends.%s.client' % settings.DATABASE_ENGINE, {}, {}, ['']
).runshell()

connection = backend.DatabaseWrapper(**settings.DATABASE_OPTIONS)
DatabaseError = backend.DatabaseError

# Register an event that closes the database connection
# when a Django request is finished.
dispatcher.connect(connection.close, signal=signals.request_finished)


# Register an event that resets connection.queries
# when a Django request is started.
def reset_queries():
    connection.queries = []


dispatcher.connect(reset_queries, signal=signals.request_started)


# Register an event that rolls back the connection
# when a Django request has an exception.
def _rollback_on_exception():
    from django.db import transaction
Beispiel #51
0
from django.db.models import signals
from django.utils.functional import curry
from django.utils.datastructures import DotExpandedDict
from django.utils.text import capfirst
from django.utils.encoding import smart_str
from django.utils.translation import ugettext as _
from django.utils import datetime_safe


def add_manipulators(sender):
    cls = sender
    cls.add_to_class('AddManipulator', AutomaticAddManipulator)
    cls.add_to_class('ChangeManipulator', AutomaticChangeManipulator)


dispatcher.connect(add_manipulators, signal=signals.class_prepared)


class ManipulatorDescriptor(object):
    # This class provides the functionality that makes the default model
    # manipulators (AddManipulator and ChangeManipulator) available via the
    # model class.
    def __init__(self, name, base):
        self.man = None  # Cache of the manipulator class.
        self.name = name
        self.base = base

    def __get__(self, instance, model=None):
        if instance != None:
            raise AttributeError, "Manipulator cannot be accessed via instance"
        else:
Beispiel #52
0
        field.do_related_class(model, cls)
    else:
        key = (app_label, model_name)
        value = (cls, field)
        pending_lookups.setdefault(key, []).append(value)
    
def do_pending_lookups(sender):
    """
    Handle any pending relations to the sending model. Sent from class_prepared.
    """
    key = (sender._meta.app_label, sender.__name__)
    for cls, field in pending_lookups.pop(key, []):
        field.rel.to = sender
        field.do_related_class(sender, cls)

dispatcher.connect(do_pending_lookups, signal=signals.class_prepared)

def manipulator_valid_rel_key(f, self, field_data, all_data):
    "Validates that the value is a valid foreign key"
    klass = f.rel.to
    try:
        klass._default_manager.get(**{f.rel.field_name: field_data})
    except klass.DoesNotExist:
        raise validators.ValidationError, _("Please enter a valid %s.") % f.verbose_name

#HACK
class RelatedField(object):
    def contribute_to_class(self, cls, name):
        sup = super(RelatedField, self)

        # Add an accessor to allow easy determination of the related query path for this field
Beispiel #53
0
        )
    else:
        raise  # If there's some other error, this must be an error in Django itself.

get_introspection_module = lambda: __import__(
    "django.db.backends.%s.introspection" % settings.DATABASE_ENGINE, {}, {}, [""]
)
get_creation_module = lambda: __import__("django.db.backends.%s.creation" % settings.DATABASE_ENGINE, {}, {}, [""])
runshell = lambda: __import__("django.db.backends.%s.client" % settings.DATABASE_ENGINE, {}, {}, [""]).runshell()

connection = backend.DatabaseWrapper(**settings.DATABASE_OPTIONS)
DatabaseError = backend.DatabaseError

# Register an event that closes the database connection
# when a Django request is finished.
dispatcher.connect(connection.close, signal=signals.request_finished)

# Register an event that resets connection.queries
# when a Django request is started.
def reset_queries():
    connection.queries = []


dispatcher.connect(reset_queries, signal=signals.request_started)

# Register an event that rolls back the connection
# when a Django request has an exception.
def _rollback_on_exception():
    from django.db import transaction

    transaction.rollback_unless_managed()
Beispiel #54
0
        self.conn = stomp.Connection(*args, **kwargs)
        self.conn.start()
        self.conn.connect()

    def disconnect(self):
        self.conn.stop()

CACHE_DELETER = CacheDeleter()


if AMQ_HOST:
    try:
        import stomp
        import socket

        # check connection to defined AMQ
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((AMQ_HOST, AMQ_PORT))
        s.close()

        # connection checked, connect CACHE_DELETER
        CACHE_DELETER.connect([(AMQ_HOST, AMQ_PORT)])

        # start listening for any model
        dispatcher.connect(CACHE_DELETER.propagate_signal, signal=signals.post_save)
        dispatcher.connect(CACHE_DELETER.propagate_signal, signal=signals.post_delete)
        log.debug('Start listening for any model')
    except:
        log.warning('ActiveMQ not running')