Flask Snippets

Wrapper for passing command-line flags to app.run()

Posted by alexwlchan on 2015-09-14 @ 07:30 and filed in Utilities

Wrapper that allows you to pass options to app.run() on the command line. Example invocations:

$ ./server.py --host 0.0.0.0
$ ./server.py --host 127.0.1.1 --port 8000
$ ./server.py --debug

Pass the --help flag to get a help message.

Here's the code, which I usually put in a separate file flaskrun.py:

import optparse

def flaskrun(app, default_host="127.0.0.1", 
                  default_port="5000"):
    """
    Takes a flask.Flask instance and runs it. Parses 
    command-line flags to configure the app.
    """

    # Set up the command-line options
    parser = optparse.OptionParser()
    parser.add_option("-H", "--host",
                      help="Hostname of the Flask app " + \
                           "[default %s]" % default_host,
                      default=default_host)
    parser.add_option("-P", "--port",
                      help="Port for the Flask app " + \
                           "[default %s]" % default_port,
                      default=default_port)

    # Two options useful for debugging purposes, but 
    # a bit dangerous so not exposed in the help message.
    parser.add_option("-d", "--debug",
                      action="store_true", dest="debug",
                      help=optparse.SUPPRESS_HELP)
    parser.add_option("-p", "--profile",
                      action="store_true", dest="profile",
                      help=optparse.SUPPRESS_HELP)

    options, _ = parser.parse_args()

    # If the user selects the profiling option, then we need
    # to do a little extra setup
    if options.profile:
        from werkzeug.contrib.profiler import ProfilerMiddleware

        app.config['PROFILE'] = True
        app.wsgi_app = ProfilerMiddleware(app.wsgi_app,
                       restrictions=[30])
        options.debug = True

    app.run(
        debug=options.debug,
        host=options.host,
        port=int(options.port)
    )

To use it with a given Flask app:

from flask import Flask
from flaskrun import flaskrun
    
app = Flask(__name__)
# do some Flask setup here
    
flaskrun(app)

You can set the default host and port on a per-app basis by passing arguments to flaskrun.

I use optparse rather than one of the fancier argument-parsing modules to ensure compatibility at least as far back as Python 2.6.

This snippet by alexwlchan can be used freely for anything you like. Consider it public domain.