SEPTEMBER 17, 2013

My flask entry point file that uses docopt

TAGS: flask, python,

I've been using Docopt - a neat library that lets you define command line arguments in a good looking, human readable docstring - in the entry point file of some of my Flask projects lately, and I thought I should share it.

It's nothing super fancy, but useful in development as it allows me to optionally specify the interface and port of the server. Here's the entry point file I use for What is my ZIP?:

""" Website

Usage: <interface:port> -h | --help

  -h --help    Show this help

import re

from docopt import docopt
from raven.contrib.flask import Sentry

from whatzip import app

if __name__ == '__main__':
    # try to parse host and port, to listen to, from command line
    arguments = docopt(__doc__, help=True)
    listen_to = arguments.get("<interface:port>")
    app_kwargs = {}
    if listen_to:
        matches = re.match("([0-9A-z.-]+):(\d{1,5})", listen_to)
        if matches:
            app_kwargs["host"] =
            app_kwargs["port"] = int(

    # run app, **app_kwargs)
    sentry = Sentry(app)

Then I can start the development server using either:


or, if I'm happy with the default interface and port, I can do:


And in production I run it through gunicorn:

gunicorn -b$PORT -k gevent web:app

The final Sentry(app) row under the else: is there to set up Sentry logging for the app, and that whole else clause can be skipped if you don't want Sentry logging in production.

Hopefully this can be useful to someone else :).


Jonatan Heyman My name is Jonatan Heyman, and I'm a programmer. On this blog I write about programming, the web and technology. I also listen to a large number of indie pop tunes. You can read more about me on the about page.



Copyright (c) 2009-2010 Jonatan Heyman