Writing a dumb little URL shortening service
Having still owned a bunch of ulost.* domains for years with no home, I finally had an idea what to do with them. Create a private URL shortening web app for myself. Granted, it’s not the shortest domain I own, but it could do the trick.
Surprisingly, the whole project wasn’t as complicated as I initially expected. I went with my framework of choice, Django to get started quickly. I threw in my coreExtend app I like to reuse for most personal projects to speed up the process a little more as well.
As for the structure itself, again, nothing too complicated. A database table for the links themselves, and another fairly basic table to track ‘clicks’. The guts of the app reside mostly in the view:
It makes a simple request to try and lookup the slug to the corresponding link object. if it does, it will attempt to store a few details about the user visiting the shortened link, two different ways. First through link_click.store(request), which writes the IP, referer (if any) user agent and a timestamp. I personally don’t need anything to sophisticated on the site end to really justify writing a whole dashboard just to view stats, so thats where Mixpanel comes in. With just a couple lines of code, I can have it sending data so I can later analyze later.
After it logs the data, it does a HttpResponseRedirect() and redirects to the original URL, all incredibly fast, even on Heroku’s free hobby plan to boot.
How shorten’ed URL’s are generated
I did want to allow a little customization for the addresses. So I have an editable slugfield in place. However, if nothing’s entered, the site will generate a random string via:
I’m using uuid to get the initial slug, then encoding it, and finally passing that string to hexdigest() to create a web safe guid. Technically, encoding it could be removed in this case, but I reuse the same code in other parts as well, so it’s easier to just let it do it’s thing to be on the safe side.
That about covers my small little weekend project. It’s fully functional and I can now create my own shortened links whenever I want. If I really wanted to, I could create my own admin, but since I'm using the basic Django ORM, that isn’t even needed as Django admin already works sufficiently. What I would like to do next at some point is finish up the API for it, to make it easier for other apps to play nice and create the shortened urls for me.
The source code is currently available on Github, at: https://github.com/underlost/ulost.net