The code for this project can be viewed on github. Google App Engine is effectively free hosting until you exceed your quotas. Just click the above link to get started and create a new instance. To develop and test locally and then deploy, use the platform appropriate version of the App engine SDK . If you don’t setup a custom domain, your app will get deployed to _appname._appspot.com .
The SDK allows you to write code and deploy locally from a particular folder of your choice.
Installing Flask
For my purposes, i needed to install the Flask python framework into the local folder because GAE can only access libraries/files you put in this folder. The command for installing flask into a particular folder is:
sudo pip install –target=<YOUR_FOLDER_HERE> flask
To know more about Flask, check out the docs here. This also installs the Jinja2 and Werkzeug libraries that Flask depends on. Once Flask was setup, all that was left was making the URL shortener!
Mapping big to small:
The skeleton of this was the following four steps:
- Take User input
- Check if valid url
- Hash url
- If hash exists in db, return shortened url from before
Else return new short url and write to db Step 1: This is done via a simple input template in python. Step 2: Here, i currently run a lame check of just verifying that every character in the input is a legal URL characters. See list of legal characters here. This is hopeless test, will be fixed later. Step 3: Here I use pythons built in hashlib, algorithm used is md5. Step 4: This requires us to deal with some form of persistent storage, we achieve this by using the GAE datastore ( done by extending the Model class) My database has records for every shortened url.
I store the hash of the input url, the input url and the short url generated. Check out database schema here. To get started creating your database, check out this page. For the different types of data you can store via the datastore API, check out this doc.
Handling short URLs:
The above four steps actually just describe a way to assign a long url to a short url, there’s nothing that handles the short urls yet!
For this part we make use of variable rules in flask. For my purposes, i have a rule setup that handles anything after /s in app.dalanm.com/s/ as an input and redirects the user appropriately.
Check out the code for url processor here.
With these things setup, our URL shortener is ready for primetime ヽ(´▽`)/
The main code is under 100 lines! The whole set up is up and running at app.dalanm.com/s.
But what about custom URLs, analytics, trending URLs, etc? Yeah all that in the next version.