Monthly Archives: August 2012

In my last post I put together a simple template server with Express running on Node for a current project. I only usually use Node for a few build tools and prefer Python on the back-end, so just for the sake of it, here’s a Python alternative.

Using Flask

Flask is a light web framework and very easy to get going with. It’s useful for putting together pages and URL routes with minimal set-up.

Using virtualenv, install with pip:

(env) $ pip install flask

Obligatory “Hello World” app, let’s call it myapp.py:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
return "Hello World!"

if __name__ == "__main__":
app.run()

Run with the following and visit localhost:5000 in your browser:

(env) $ python myapp.py

Templates use Jinja2, which would have been installed as a dependency when you grabbed Flask.

Syntactically It’s very similar to Django’s templating:

<title>{% block title %}User list{% endblock %}</title>
<ul>
{% for user in users %}
<li><a href="{{ user.url }}">{{ user.username }}</a></li>
{% endfor %}
</ul>

The block tag is used for template inheritance, which is far more useful than including partials everywhere.

For example, a second template can extend the above to reuse the loop logic but update the page title:

{% extends "base.html" %}
{% block title %}Here’s a new title!{% endblock %}

N.B. Since Express matured to 3.x it’s view system concept is going that way too — see migration docs.

Flask provides a render_template method looking for files in a directory named templates, which will sit alongside our application file:

@app.route('/')
def simple():
return render_template('simple.html', message=”Hello World”)

Working with data

Flask’s render_template method sends a view context (dictionary) to the templates, for example the message above. Jinja isn’t logic-less like Mustache, so we can use this context for conditionals, loops and filters.

Refactoring our Javascript code, we can use regular Python load some JSON:

def get_json(path):
file = open(path)
data = json.load(file)
file.close()
return data

@app.route('/')
def simple():
data = get_json(‘data/simple.json’)
return render_template('simple.html', **data)

JSON is far more suited to the other implementation, being entirely Javascript-based.

I can’t say I’ve ever used this approach, for front-end (only) builds I’d just work with a few variables to switch in templates and likely have a shared dictionary for ‘global’ data, e.g. placeholder user info.

On larger projects with back-end work I’d go for Django and a full relational database, though here we’re using static data files.

As for static media files, CSS et al, Flask serves from a static folder which sits alongside our app file and templates directory — this doesn’t have to be specified in the application logic, unlike Express.

Of course, Flask can be used for fully featured applications, three examples:

The Flask Snippets archive is also a great resource, user-provided pieces of code to bootstrap your application — auth, forms, security, sessions etc.

Source files: simple-flask on Github.

I’m currently working on a front-end build for a site whilst a second (external) team simultaneously develop the back-end. Those guys will later integrate the templates once everything is ready. It’s a fairly common scenario.

We’re in a good position with this project specifically, because although the server-side is a work in progress the developers have provided a full API specification that details all the data that the application will provide, in its entirety. Our work isn’t held up by any architectural decisions yet to be made – the spec is finalised, only the platform to serve data and render our views doesn’t exist yet.

Working from spec, we’re able to create accurate (dummy) data objects and render pages with a templating system to build a limited, realistic, navigable version of the site.

With our data objects in line with their schemas, plus agreeing on a templating system similar to their implementation, should minimise the integration period.

For templating we’re using Mustache, which has a number of server-side and client-side implementation options.

The project is also built with Bootstrap, which makes use of LESS CSS.

Working with LESS, Bootstrap or otherwise, I use the command-line compiler with a custom script to monitors file changes and automatically output the master CSS file as I go. This runs using Jake, a Javascript build tool for Node.js, which I also use to compile and minify Javascript files, plus a few other tasks.

We decided to build on the Node stack with a Javascript implementation of Mustache and a light web framework, Express, to serve our pages and provide URL routing.

Using Express

With Node installed, get Express with npm:

mkdir myapp
cd myapp
npm install express

Create a basic Hello World app in a text file, myapp.js:

var express = require('express'),
app = express();

app.get('/', function(req, res) {
res.send('Hello World');
});

app.listen(3000);
console.log('Listening on port 3000');

Run with the following and visit localhost:3000 in your browser:

node myapp.js

To serve a template with data you’ll need to install a templating engine, create the view and update the app response. The default is Jade:

npm install jade

Create the view file in the default views directory, called simple.jade – print the data:

=message

Update and restart the app file:

app.get('/', function(req, res) {
res.render('simple.jade', {'message': 'Hello World'});
});

Node Toolbox

Restarting the app gets old fast, install nodemon globally to monitor the script for changes and the reload will be automatic:

npm install nodemon -g
nodemon myapp.js

Express will look at the view name extension to load the templating engine. To switch to another, e.g. Mustache, install and configure the app to use a different module. Not all engines provide the same method for Express to render templates, so Consolidate.js maps a bunch of popular options automatically.

npm install consolidate mustache

var engines = require('consolidate');
app.engine('mustache', engines.mustache);

app.get('/', function(req, res) {
res.render('simple.mustache', {'message': 'Hello World'});
});

Update the view with Mustache syntax:

{{ message }}

Also use the engine method to map the .html extension so you don’t have to use .mustache files if you like. The view engine setting saves you from writing the extension in the render method too:

app.engine('html', engines.mustache);
app.set('view engine', 'html');

app.get('/', function(req, res) {
res.render('simple', {'message': 'Hello World'});
});

It’s not great having to write JSON data inline, so use fs to read your JSON from separate files with something like the following:

var fs = require(‘fs’);

var getJSON = function(path) {
var fileContents = fs.readFileSync(path, 'utf8');
return JSON.parse(fileContents);
}

app.get('/', function(req, res) {
var data = getJSON('views/simple.json');
res.render('simple', data);
}

We also wanted support for partials, so we moved to Hogan.js,  a Mustache compiler from Twitter.

Since our environment runs entirely on Node, we’re also able to make use of some freebie cloud hosting, the likes of Heroku and Nodejitsu, for staging at least.

Dependencies for Node projects can be described in a package manifest, specifying modules and version requirements. Our package.json file, in the directory root, looks like this:

{
"name": "simple-express",
"description": "Simple Express template server",
"version": "0.0.1",
"dependencies": {
"express": "3.x",
"nodemon": "0.6.19",
"consolidate": "0.4.0",
"mustache": "0.5.2"
}
}

With a manifest you can run a single command to grab everything you need:

npm install

Nodejitsu use package files to deploy applications, they’ve got a handy interactive cheat sheet exploring the various properties.

Source files: simple-express on Github.

Sometimes it might seem like it was planned.