Source

jcosta-django-articles / articles / decorators.py

import functools
import logging
import time

log = logging.getLogger('articles.decorators')

def logtime(func):

    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        if func.__class__.__name__ == 'function':
            executing = '%s.%s' % (func.__module__, func.__name__)
        elif 'method' in func.__class__.__name__:
            executing = '%s.%s.%s' % (func.__module__, func.__class__.__name__, func.__name__)
        else:
            executing = str(func)

        log.debug('Logging execution time for %s with args: %s; kwargs: %s' % (executing, args, kwargs))

        start = time.time()
        res = func(*args, **kwargs)
        duration = time.time() - start

        log.debug('Called %s... duration: %s seconds' % (executing, duration))
        return res

    return wrapped

def once_per_instance(func):
    """Makes it so an instance method is called at most once before saving"""

    @functools.wraps(func)
    def wrapped(self, *args, **kwargs):
        if not hasattr(self, '__run_once_methods'):
            self.__run_once_methods = []

        name = func.__name__
        if name in self.__run_once_methods:
            log.debug('Method %s has already been called for %s... not calling again.' % (name, self))
            return False

        res = func(self, *args, **kwargs)

        self.__run_once_methods.append(name)
        return res

    return wrapped
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.