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 argparse
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 = argparse.ArgumentParser(description="An example usage of command \
line arguments for a flask app.")
parser.add_argument("-H", "--host",
help="Hostname of the Flask app " + \
"[default %s]" % default_host,
default=default_host)
parser.add_argument("-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_argument("-d", "--debug",
action="store_true", dest="debug")
parser.add_argument("-p", "--profile",
action="store_true", dest="profile")
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.
Notes: Forked and updated from flask snippet 133