TinyUrl clone
posted in programming by jon on 2007-07-10
Yesterday, while listening to lugradio, I heard Aq mention someone creating a tinyurl clone that allowed you to specify your own link "handle" to reference the url (tinyurl uses a random alphanumeric id). That got me thinking about the usefulness of having my own personal url aliasing service. I use del.icio.us to manage my bookmarks, but I can definitely see the use-case for named, shortcut bookmarks for things of particular interest.
My second thought was how trivial this would be to implement in django. Result: 44 lines of code and 75 lines of html later, and I have my own tinyurl service. You can see the working implementation here (disclaimer: don't assume it's remotely bug-free, secure, or well implemented.)
the model
from django.db import models class Link(models.Model): handle = models.CharField(maxlength=255,unique=True) url = models.CharField(maxlength=255) def __str__(self): return self.handle class Admin: pass
The views
from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponseNotFound from django.shortcuts import render_to_response, get_object_or_404 from django.newforms import form_for_model from django.utils import simplejson from jonallie.tinylink.models import Link def index(request): LinkForm = form_for_model(Link) message = "" if request.method == 'POST': form = LinkForm(request.POST) if form.is_valid(): form.save() message = "Form saved: access your new link at http://jonallie.com/tinylink/go/%s" % form.data['handle'] form = LinkForm() else: message = "Form NOT saved. Check errors below" else: form = LinkForm() return render_to_response('tinylink/index.html',{'form':form,'message':message}) def redirect(request,link_handle): link = get_object_or_404(Link, handle=link_handle) return HttpResponseRedirect(link.url) def check_handle(request,link_handle): link = get_object_or_404(Link,handle=link_handle) return HttpResponse(simplejson.dumps({'handle':link.handle}), mimetype='application/javascript')
Subscribe 