Login

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

Author:
simon
Posted:
April 11, 2009
Language:
Python
Version:
1.0
Score:
3 (after 3 ratings)

Slightly shonky implementation of a custom URL shortening view, as described on my blog. Depends on baseconv.py

 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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 4 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

Please login first before commenting.