Flask Command Line Script

Feb 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.

flask

Create a Shell Script

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

export FLASK_APP=myapp.py# optional debug modeexport FLASK_DEBUG=1flask

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 clickfrom flask import Flaskapp = Flask(__name__)@app.cli.command()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.

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.