Flask Command Line Script

February 13, 2018
flask cli

Web app usually need some command line script for cronjob or other tasks. If you are using Flask, flask cli (used to be flask-script) make it easy to write command line script with easy access to your existing app’s configurations, SQLAlchemy models, WTForms, etc.

First, you need to install Flask (in your virtualenv probably) so that you can access the flask command.

pip install Flask

Check if the flask command is available.


Create a Shell Script

Create a shell script (e.g. flask_test.sh) with the following content.

export FLASK_APP=myapp.py
# optional debug mode
export FLASK_DEBUG=1

NOTE: assuming myapp.py contains a flask app object named app (e.g. app = Flask(__name__)). If your app object is named something else, you can specifiy the app object name by using export FLASK_APP=myapp:application.

NOTE: if you app file is a module, you can use export FLASK_APP=/path/myapp/__init__.py (is there a better way?)

Test the script.

source flask_test.sh

Create commands

Add a command for flask cli by editing your flask app file.

import click
from flask import Flask

app = Flask(__name__)

def test():
    click.echo('I am test')

Test the command.

flask test

Flask comes with 2 default commands:

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


This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.