# HG changeset patch # User Tero Marttila # Date 1378559862 -10800 # Node ID 88d9c9974d6a05c45950f485906b2692a793d770 # Parent 656c8ff72f7741a19f59e386943c54a51dc36b6c move get_url to URL diff -r 656c8ff72f77 -r 88d9c9974d6a qrurls/models.py --- a/qrurls/models.py Sat Sep 07 16:15:34 2013 +0300 +++ b/qrurls/models.py Sat Sep 07 16:17:42 2013 +0300 @@ -64,6 +64,33 @@ def cache_key (self, shorturl) : return 'qrurls/url/{shorturl}'.format(shorturl=shorturl) + @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.DoesNotExist + """ + key = cls.cache_key(shorturl) + get = cache.get(key) + + if get : + log.debug("get cache: %s", key) + return get + else: + # from db + url_item = URLItem.get(shorturl=shorturl) + set = ( + url_item.get_absolute_url(), + url_item.last_modified() + ) + + log.debug("set cache: %s", key) + cache.set(key, set) + return set + + def qrcode_img (self, size=512) : return QRCODE_API.format( width=size, height=size, @@ -189,16 +216,12 @@ ordering = ['published'] @classmethod - def cache_key (cls, shorturl, item_id) : - return 'qrurls/url/{shorturl}/{item}'.format(shorturl=shorturl, item=item_id) - - @classmethod def get (cls, shorturl, item_id=None, related=()) : """ Return the URLItem for a given shorturl, either the given specific one, - or the latest, from the database. + or the latest, from the database in one SQL query. - Raises URLItem.NotFound + Raises URLItem.DoesNotExist """ # JOIN against shorturl, urlimage url_item = cls.objects.select_related(*related) @@ -229,30 +252,8 @@ raise cls.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 = URL.cache_key(shorturl) - get = cache.get(key) - - if get : - log.debug("get cache: %s", key) - return get - else: - # from db - url_item = cls.get(shorturl=shorturl) - set = ( - url_item.get_absolute_url(), - url_item.last_modified() - ) - - log.debug("set cache: %s", key) - cache.set(key, set) - return set + def cache_key (cls, shorturl, item_id) : + return 'qrurls/url/{shorturl}/{item}'.format(shorturl=shorturl, item=item_id) @classmethod def get_item (cls, shorturl, item_id) : @@ -260,7 +261,7 @@ Return a data dict for the given URLItem, from cache or DB. Returns { url: str, title: str, image: str, last_modified: datetime } - Raises URLItem.NotFound + Raises URLItem.DoesNotExist """ key = cls.cache_key(shorturl, item_id) diff -r 656c8ff72f77 -r 88d9c9974d6a qrurls/views.py --- a/qrurls/views.py Sat Sep 07 16:15:34 2013 +0300 +++ b/qrurls/views.py Sat Sep 07 16:17:42 2013 +0300 @@ -28,7 +28,7 @@ """ try: - url, modified = URLItem.get_url(shorturl) + url, modified = URL.get_url(shorturl) except URLItem.DoesNotExist: raise Http404()