Project 2

This assignment is to write a Flask application that enables the user to browse books about Queen Elizabeth I. It is due on March 8, 2016.


This is a team assignment, so you must complete and submit it with your team.


The purpose of this assignment is to create a URL shortener that maintains a list of short URLs.

A URL shortener takes a URL, stores it in its storage, and assigns it a short code. The code can then be used to go to the (long) URL.

Revision Log

February 29
Added .decode('ascii') to shortening instructions

Getting Started

Create a project as you have for the other assignments.

Index page

The index page (/) for your app should have a suitable title, and a form to create a new URL.

This form should consist of a text field for the URL (called url) and a submit button labeled ‘Shorten!’.

The form should POST its results to the url /shorten

Handling /shorten

Once you have a form, you need to handle the /shorten URL.

It should generate a random key; it can do this with1:

import uuid
import base64
key = base64.urlsafe_b64encode(uuid.uuid4().bytes)[:12].decode('ascii')
# sample value: 1Ctu77qhTaSS

The [:12] syntax is called a slice: it selects indexes 0 through 11 (inclusive).

Once you have a random key, save the URL and key into a global dictionary that you have created for the purpose. Use the key as the key, and the URL as the value.

Then, redirect the user to the link's Preview page, /‹key›?preview=1.

When they user visits the URL /‹key›, the Flask should look up ‹key› in the global shortening dictionary, and do the following:

  • If ‹key› is a valid URL key, return an HTTP 301 redirect to the URL (using flask.redirect).
  • Otherwise, return an HTTP 404 error.

There's one more thing you need to do. Modify your URL handler for /‹key›, and before you return the key, check if the preview query parameter was provided (it'll be a key in the dictionary flask.requests.args). If so, then instead of returning a redirect to the URL, return a page that tells the user what URL the specified key will redirect to.

Saving and Restoring Data

One final thing. Once you have everything working, it's time to make it so that data doesn't get discarded every time the server shuts down. There are two pieces of this:

  1. In the handler for /shorten, after updating the dictionary, save the dictionary to a JSON file. Like so:

    with open('bookmarks.json', 'w') as f:
        json.dump(urls, f)
  2. When your program starts up, if the file bookmarks.json exists (you can test this with os.path.exists), load the data from it into your urls dictionary.

Other Concerns

You should use CSS styling to give your application a reasonable appearance.


Prepare your submission using package.

Only one team member should submit.