chevron-up bell reply instagram twitter2 feed3 finder search-25px-p0

Flask Command Line

2018-01-09

Happy New Year! Hope everything becomes better in 2018!

From the version 0.11.0, Flask began to support shell command. Something you probably you already saw when you are using other web project, such as Django:

./manage.py shell

To achieve that, it is quite simple as it only needs two steps:
1. Set up the environment. To let flask know where is app variable. In my case, app is defined in the __init__.py:

app = Flask(__name__)

So to set up the global flask environment:

export FLASK_APP=application/__init__.py

2. Set up commands:
2.1 Command without parameters

@app.cli.command()
def echo():
    """
    Echo function without parameter
    """
    print "echo"

Then the echo() function can be run in the shell:

flask echo

2.2 Command with parameters. Need to install click lib by pip install click.

@app.cli.command()
@click.argument('parameter')
def echo(parameter):
    """
    Echo function with parameter
    """
    print "echo {}".format(parameter)

run echo() function in the shell:

flask echo "ok"

Even you can run without the double quotation of the string:

flask echo ok

List all the built-in commands:

flask

It will output:

Usage: flask [OPTIONS] COMMAND [ARGS]...

This shell command acts as general utility script for Flask applications.

It loads the application configured (through the FLASK_APP environment
variable) and then provides commands either provided by the application or
Flask itself.

The most useful commands are the "run" and "shell" command.

Example usage:

$ export FLASK_APP=hello.py
$ export FLASK_DEBUG=1
$ flask run

Options:
--version Show the flask version
--help Show this message and exit.

Commands:
echo
run Runs a development server.
shell Runs a shell in the app context.

Reference

http://www.arkilis.me/?p=941
http://flask.pocoo.org/docs/0.12/cli/

arkilis

Make Your Comments