2014-01-04

Flask TodoMVC Part 1

This is the first article in the Flask TodoMVC tutorial, a series that creates a Backbone.js backend with Flask for the TodoMVC app. In this article, we will create a Flask app using the Backbone.js example as a starting point. Future articles will replace the localStorage persistence with a database backend and a RESTFul API.

To begin, let's download the TodoMVC example as a starting point. We are only interested in the Backbone.js example, so we create an empty repository and copy the files.

$ cd ~/Projects
$ git clone https://github.com/tastejs/todomvc
$ mkdir flask-todomvc
$ cp -R todomvc/architecture-examples/backbone flask-todomvc
$ cd flask-todomvc/backbone
$ python -m  SimpleHTTPServer  # or python3 -m http.server

Open a browser to localhost:8000 and click around. You already have a working Todo list. Are we done? Well, we could be. But the current list persists all items to localStorage so they are only available from the current browser. Let's transform this to a simple Flask app.

Hello World

Start by creating the obligatory Hello World. Create a file called server.py in your flask-todomvc directory.

""" server.py """
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello world'

if __name__ == '__main__':
    app.run(port=8000)

Create a virtualenv and install Flask. This example uses virtualenvwrapper, but it is not required.

$ cd ~/Projects/flask-todomvc 
$ mkvirtualenv flask-todomvc
$ setvirtualenvproject
$ pip install Flask
$ python server.py

Open a browser to localhost:8000 and view your greeting.

Serve TodoMVC from Flask

Now that we have a basic Flask app, let's change it so it serves the TodoMVC example. We are going to use the default Flask structure with static and templates directories. Let's create those and move the example files into the appropriate place.

$ mkdir {static,templates}
$ mv backbone/{js,bower_components} static
$ mv backbone/index.html templates
$ rm -r backbone

Now edit server.py to serve the todo list by changing the following.

  1. Import render_template
  2. Render the index.html template on route to index.
  3. Configure static_url_path to the empty string.

We do the last step so that the static assets are served from the index instead of prepended with /static. Alternatively we could edit the index.html template to use url_for on all references to static files.

""" server.py """
from flask import Flask, render_template

app = Flask(__name__, static_url_path='')

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(port=8000)

Start the flask server, open a browser and view your todo list.

Conclusion

What have we accomplished? We have created a Flask app to serve the Backbone.js example from TodoMVC. In the next article we will build on this app to provide server side synchronization of the Todo items.

The code is available on GitHub with tag part1.