models.py 8.87 KB
Newer Older
Őry Máté committed
1
from collections import deque
2
from contextlib import contextmanager
3
from hashlib import sha224
4
from logging import getLogger
5 6
from time import time

7
from django.contrib.auth.models import User
8
from django.core.cache import cache
9 10
from django.db.models import (CharField, DateTimeField, ForeignKey,
                              NullBooleanField, TextField)
11 12
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
13

14 15
from model_utils.models import TimeStampedModel

16 17
logger = getLogger(__name__)

18

19 20 21 22
class WorkerNotFound(Exception):
    pass


23
def activitycontextimpl(act, on_abort=None, on_commit=None):
24 25
    try:
        yield act
26 27 28
    except BaseException as e:
        # BaseException is the common parent of Exception and
        # system-exiting exceptions, e.g. KeyboardInterrupt
29 30
        handler = None if on_abort is None else lambda a: on_abort(a, e)
        act.finish(succeeded=False, result=str(e), event_handler=handler)
31 32
        raise e
    else:
33
        act.finish(succeeded=True, event_handler=on_commit)
34 35


36 37 38
activity_context = contextmanager(activitycontextimpl)


39 40 41 42 43 44 45 46 47
activity_code_separator = '.'


def join_activity_code(*args):
    """Join the specified parts into an activity code.
    """
    return activity_code_separator.join(args)


48 49
class ActivityModel(TimeStampedModel):
    activity_code = CharField(max_length=100, verbose_name=_('activity code'))
50
    parent = ForeignKey('self', blank=True, null=True, related_name='children')
51 52 53 54 55 56 57 58 59 60 61
    task_uuid = CharField(blank=True, max_length=50, null=True, unique=True,
                          help_text=_('Celery task unique identifier.'),
                          verbose_name=_('task_uuid'))
    user = ForeignKey(User, blank=True, null=True, verbose_name=_('user'),
                      help_text=_('The person who started this activity.'))
    started = DateTimeField(verbose_name=_('started at'),
                            blank=True, null=True,
                            help_text=_('Time of activity initiation.'))
    finished = DateTimeField(verbose_name=_('finished at'),
                             blank=True, null=True,
                             help_text=_('Time of activity finalization.'))
62 63 64
    succeeded = NullBooleanField(blank=True, null=True,
                                 help_text=_('True, if the activity has '
                                             'finished successfully.'))
65 66 67
    result = TextField(verbose_name=_('result'), blank=True, null=True,
                       help_text=_('Human readable result of activity.'))

68 69 70 71 72 73
    def __unicode__(self):
        if self.parent:
            return self.parent.activity_code + "->" + self.activity_code
        else:
            return self.activity_code

74 75 76
    class Meta:
        abstract = True

77
    def finish(self, succeeded, result=None, event_handler=None):
78 79
        if not self.finished:
            self.finished = timezone.now()
80
            self.succeeded = succeeded
81 82
            if result is not None:
                self.result = result
83 84
            if event_handler is not None:
                event_handler(self)
85
            self.save()
86

87 88 89 90 91 92 93 94
    @property
    def has_succeeded(self):
        return self.finished and self.succeeded

    @property
    def has_failed(self):
        return self.finished and not self.succeeded

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

def method_cache(memcached_seconds=60, instance_seconds=5):  # noqa
    """Cache return value of decorated method to memcached and memory.

    :param memcached_seconds: Invalidate memcached results after this time.
    :param instance_seconds: Invalidate results cached to static memory after
    this time.

    If a result is cached on instance, return that first.  If that fails, check
    memcached. If all else fails, run the method and cache on instance and in
    memcached.

    Do not use for methods with side effects.
    Instances are hashed by their id attribute, args by their unicode
    representation.

    ** NOTE: Methods that return None are always "recached".
    Based on https://djangosnippets.org/snippets/2477/
    """

    def inner_cache(method):

        def get_key(instance, *args, **kwargs):
            return sha224(unicode(method.__module__) +
                          unicode(method.__name__) +
                          unicode(instance.id) +
                          unicode(args) +
                          unicode(kwargs)).hexdigest()

        def x(instance, *args, **kwargs):
            invalidate = kwargs.pop('invalidate_cache', False)
            now = time()
            key = get_key(instance, *args, **kwargs)

            result = None
            try:
                vals = getattr(instance, key)
            except AttributeError:
                pass
            else:
                if vals['time'] + instance_seconds > now:
                    # has valid on class cache, return that
                    result = vals['value']

            if result is None:
                result = cache.get(key)

            if invalidate or (result is None):
                # all caches failed, call the actual method
                result = method(instance, *args, **kwargs)
                # save to memcache and class attr
                cache.set(key, result, memcached_seconds)
                setattr(instance, key, {'time': now, 'value': result})
148 149 150
                logger.debug('Value of <%s>.%s(%s)=<%s> saved to cache.',
                             unicode(instance), method.__name__,
                             unicode(args), unicode(result))
151 152 153 154 155

            return result
        return x

    return inner_cache
Őry Máté committed
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189


class HumanSortField(CharField):
    """
    A CharField that monitors another field on the same model and sets itself
    to a normalized value, which can be used for sensible lexicographycal
    sorting for fields containing numerals. (Avoiding technically correct
    orderings like [a1, a10, a2], which can be annoying for file or host
    names.)

    Apart from CharField's default arguments, an argument is requered:
        - monitor   sets the base field, whose value is normalized.
        - maximum_number_length    can also be provided, and defaults to 4. If
        you have to sort values containing numbers greater than 9999, you
        should increase it.

    Code is based on carljm's django-model-utils.
    """
    def __init__(self, *args, **kwargs):
        logger.debug('Initing HumanSortField(%s %s)',
                     unicode(args), unicode(kwargs))
        kwargs.setdefault('default', "")
        self.maximum_number_length = kwargs.pop('maximum_number_length', 4)
        monitor = kwargs.pop('monitor', None)
        if not monitor:
            raise TypeError(
                '%s requires a "monitor" argument' % self.__class__.__name__)
        self.monitor = monitor
        kwargs['blank'] = True
        super(HumanSortField, self).__init__(*args, **kwargs)

    def get_monitored_value(self, instance):
        return getattr(instance, self.monitor)

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
    @staticmethod
    def _partition(s, pred):
        """Partition a deque of chars to a tuple of a
           - string of the longest prefix matching pred,
           - string of the longest prefix after the former one not matching,
           - deque of the remaining characters.

           >>> HumanSortField._partition(deque("1234abc567"),
           ...                           lambda s: s.isdigit())
           ('1234', 'abc', deque(['5', '6', '7']))
           >>> HumanSortField._partition(deque("12ab"), lambda s: s.isalpha())
           ('', '12', deque(['a', 'b']))
        """
        match, notmatch = deque(), deque()
        while s and pred(s[0]):
            match.append(s.popleft())
        while s and not pred(s[0]):
            notmatch.append(s.popleft())
        return (''.join(match), ''.join(notmatch), s)
Őry Máté committed
209

210
    def get_normalized_value(self, val):
Őry Máté committed
211 212 213 214
        logger.debug('Normalizing value: %s', val)
        norm = ""
        val = deque(val)
        while val:
215 216 217 218
            numbers, letters, val = self._partition(val,
                                                    lambda s: s[0].isdigit())
            if numbers:
                norm += numbers.rjust(self.maximum_number_length, '0')
Őry Máté committed
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
            norm += letters
        logger.debug('Normalized value: %s', norm)
        return norm

    def pre_save(self, model_instance, add):
        logger.debug('Pre-saving %s.%s. %s',
                     model_instance, self.attname, add)
        value = self.get_normalized_value(
            self.get_monitored_value(model_instance))
        setattr(model_instance, self.attname, value[:self.max_length])
        return super(HumanSortField, self).pre_save(model_instance, add)

# allow South to handle these fields smoothly
try:
    from south.modelsinspector import add_introspection_rules
    add_introspection_rules(rules=[
        (
            (HumanSortField,),
            [],
            {'monitor': ('monitor', {}),
             'maximum_number_length': ('maximum_number_length', {}), }
        ),
    ], patterns=['common\.models\.'])
except ImportError:
    pass