diff options
Diffstat (limited to 'main/utils.py')
-rw-r--r-- | main/utils.py | 60 |
1 files changed, 49 insertions, 11 deletions
diff --git a/main/utils.py b/main/utils.py index e7e47c53..cdd4ff71 100644 --- a/main/utils.py +++ b/main/utils.py @@ -5,9 +5,11 @@ except ImportError: from datetime import datetime import hashlib -from pytz import utc from django.core.cache import cache +from django.db import connections, router +from django.utils.timezone import now +from django.template.defaultfilters import slugify CACHE_TIMEOUT = 1800 @@ -52,6 +54,16 @@ def clear_cache_function(func, args, kwargs): key = cache_function_key(func, args, kwargs) cache.delete(key) + +def format_http_headers(request): + headers = sorted((k, v) for k, v in request.META.items() + if k.startswith('HTTP_')) + data = [] + for k, v in headers: + data.extend([k[5:].replace('_', '-').title(), ': ', v, '\n']) + return ''.join(data) + + # utility to make a pair of django choices make_choice = lambda l: [(str(m), str(m)) for m in l] @@ -72,7 +84,7 @@ def refresh_latest(**kwargs): cache.set(cache_key, None, INVALIDATE_TIMEOUT) -def retrieve_latest(sender): +def retrieve_latest(sender, latest_by=None): # we could break this down based on the request url, but it would probably # cost us more in query time to do so. cache_key = CACHE_LATEST_PREFIX + sender.__name__ @@ -80,8 +92,9 @@ def retrieve_latest(sender): if latest: return latest try: - latest_by = sender._meta.get_latest_by - latest = sender.objects.values(latest_by).latest()[latest_by] + if latest_by is None: + latest_by = sender._meta.get_latest_by + latest = sender.objects.values(latest_by).latest(latest_by)[latest_by] # Using add means "don't overwrite anything in there". What could be in # there is an explicit None value that our refresh signal set, which # means we want to avoid race condition possibilities for a bit. @@ -92,17 +105,42 @@ def retrieve_latest(sender): return None -def utc_now(): - '''Returns a timezone-aware UTC date representing now.''' - return datetime.utcnow().replace(tzinfo=utc) - - def set_created_field(sender, **kwargs): '''This will set the 'created' field on any object to the current UTC time - if it is unset. For use as a pre_save signal handler.''' + if it is unset. + Additionally, this will set the 'last_modified' field on any object to the + current UTC time on any save of the object. + For use as a pre_save signal handler.''' obj = kwargs['instance'] + time = now() if hasattr(obj, 'created') and not obj.created: - obj.created = utc_now() + obj.created = time + if hasattr(obj, 'last_modified'): + obj.last_modified = time + + +def find_unique_slug(model, title): + '''Attempt to find a unique slug for this model with given title.''' + existing = set(model.objects.values_list( + 'slug', flat=True).order_by().distinct()) + + suffixed = slug = slugify(title) + suffix = 0 + while suffixed in existing: + suffix += 1 + suffixed = "%s-%d" % (slug, suffix) + + return suffixed + + +def database_vendor(model, mode='read'): + if mode == 'read': + database = router.db_for_read(model) + elif mode == 'write': + database = router.db_for_write(model) + else: + raise Exception('Invalid database mode specified') + return connections[database].vendor def groupby_preserve_order(iterable, keyfunc): |