qrurls/models.py
changeset 82 6442e5c97b48
parent 81 3a2fdc820c41
child 83 35bdf2acbbaa
--- a/qrurls/models.py	Sat Sep 07 15:38:24 2013 +0300
+++ b/qrurls/models.py	Sat Sep 07 15:48:23 2013 +0300
@@ -3,11 +3,12 @@
 import logging
 import os.path
 
-from django.db import models
 import django.core.files.storage
-from django.core.urlresolvers import reverse
 import django.utils.http
 from django.contrib.sites.models import get_current_site
+from django.core.cache import cache
+from django.core.urlresolvers import reverse
+from django.db import models
 from django.utils import timezone
 
 log = logging.getLogger('qrurls.models')
@@ -183,7 +184,7 @@
         ordering = ['published']
 
     @classmethod
-    def search (cls, shorturl=None, item_id=None, related=()) :
+    def get_item (cls, shorturl, item_id=None, related=()) :
         """
             Return the URLItem for a given shorturl, either the given specific one,
             or the latest, from the database.
@@ -204,19 +205,48 @@
         # match for published items
         now = timezone.now()
         url_item = url_item.filter(published__lt=now).order_by('-published')
-        
-        log.info("Search URLItem @ %s", now)
        
         if item_id :
             # specific, but still the published on
-            return url_item.get(id=int(item_id)) # raises DoesNotExist
+            item_id = int(item_id)
+            log.debug("search @ %d", item_id)
+
+            return url_item.get(id=item_id) # raises DoesNotExist
         else :
             # most recent
+            log.debug("search @ %s", now)
             try:
                 return url_item[0]
             except IndexError:
                 raise DoesNotExist()
 
+    @classmethod
+    def get_url (cls, shorturl) :
+        """
+            Return the current URL for a given shorturl, from cache or DB.
+            
+            Returns url:str, modified:datetime
+            Raises URLItem.NotFound
+        """
+
+        key = 'qrurls/url/{shorturl}'.format(shorturl=shorturl)
+        get = cache.get(key)
+        
+        if get :
+            url, modified = get
+            log.debug("get cache: %s: %s", key, url)
+        else:
+            # from db
+            url_item = cls.get_item(shorturl=shorturl)
+
+            url = url_item.get_absolute_url()
+            modified = url_item.last_modified()
+            
+            log.debug("set cache: %s: %s", key, url)
+            cache.set(key, (url, modified)) # XXX: expiry
+        
+        return url, modified
+
     def get_absolute_url (self) :
         if self.url :
             return self.url