A custom URL shortening view, for use with rev=canonical

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from blog.models import Entry, Blogmark, Quotation
from baseconv import base62
from django.http import HttpResponsePermanentRedirect, Http404
from django.shortcuts import get_object_or_404

BASE_URL = 'http://simonwillison.net'
SHORT_BASE_URL = 'http://swtiny.eu/'
PREFIXES = {
    'E': Entry,
    'B': Blogmark,
    'Q': Quotation,
}

def redirect_view(request, tiny):
    "This should be hooked up to /shorten/(.*) in the URLconf"
    if not tiny:
        return HttpResponsePermanentRedirect(BASE_URL + '/')
    prefix = tiny[0]
    tiny = tiny[1:]
    try:
       model = PREFIXES[prefix] 
       id = base62.to_decimal(tiny)
    except (ValueError, KeyError):
       raise Http404
    obj = get_object_or_404(model, pk = id)
    url = obj.get_absolute_url()
    if not url.startswith('http://') and not url.startswith('https://'):
        url = BASE_URL + url
    return HttpResponsePermanentRedirect(url)

def shorten(obj):
    "Returns a shorter URL for a Django model object, or None if not available"
    found = None
    for prefix, model in PREFIXES.items():
        if model._meta.db_table == obj._meta.db_table:
            found = prefix
    if not found:
        return None
    return SHORT_BASE_URL + found + base62.from_decimal(obj.id)

More like this

  1. Bit.ly url shortener by BluePeppers 3 years, 4 months ago
  2. Goo.gl URL shortener by aabele 3 years, 6 months ago
  3. int_to_base36 and base36_to_int by simon 5 years, 9 months ago
  4. simple text image view by derelm 7 years, 1 month ago
  5. Create short URL redirects for site urls. by matt.geek.nz 5 years, 2 months ago

Comments

(Forgotten your password?)