Hello Coders,
This article presents a Flask sample project that implements custom commands on top of Flask Command-Line interface. Custom commands might be useful to implement maintenance tasks, inspect the application state in production, or simply to load new records into the database using a JSON file as input. The code, available on Github, can be extended with ease to cover more useful use-cases.
Thank you! Content provided by App Generator.
- Flask Command-Line - sample project
- Flask Black Dashboard - the original starter
How to use the code
The sample code can be compiled with a few commands typed in the terminal if a Python3 environment is up & running on our workspace. The first step is to clone the project:
$ # Get the code
$ git clone https://github.com/app-generator/flask-command-line.git
$ cd flask-command-line
Install modules and set up the environment:
$ # Virtualenv modules installation (Unix based systems)
$ virtualenv env
$ source env/bin/activate
$
$ # Install dependencies
$ pip3 install -r requirements.txt
$
$ export FLASK_APP=run.py
At this point, the app is ready to be executed and we can list the registered (new) commands:
$ # List the new commands
$ flask commands
Usage: flask commands [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
cfg List all Config Variables <-- NEW Command
hello Simple Hello <-- NEW Command
The "Commands" node shows two commands that we can invoke and check the results:
$ flask commands hello
Custom command - Hello <- The Output
Our first command is fairly simple: prints a "Hello" message. The code can be found in the "commands" Blueprint:
@commands.cli.command('hello')
def hello():
""" Simple Hello """
print("Custom command - Hello")
With the second custom command we are getting closer to something useful: list the configuration variables and optionally filter the output using an input string.
Here is the code - defined in the same file (commands.py):
@commands.cli.command('cfg')
@click.argument('filter', required=False)
def config(filter=None):
""" List all Config Variables """
print("Custom command - Cfg(Filter="+str(filter)+")")
for key in current_app.config:
val = str( current_app.config[key] )
# Filtered config
if filter:
if re.search(filter, key, re.IGNORECASE):
print ( ' |- ' + key + ' -> ' + val )
# Unfiltered config
else:
print ( ' |- ' + key + ' -> ' + val )
The above code read an optional parameter "filter" and iterate over the application config variables. If the "filter" parameter is defined, only the keys that match the filter are listed.
The Custom COMMAND
$ # Unfiltered output (list all keys)
$ flask commands cfg
The OUTPUT
Custom command - Cfg(Filter=None)
|- ENV -> production
|- DEBUG -> False
|- TESTING -> False
|- PROPAGATE_EXCEPTIONS -> None
|- PRESERVE_CONTEXT_ON_EXCEPTION -> None
|- SECRET_KEY -> S3cr3t_K#Key
|- PERMANENT_SESSION_LIFETIME -> 31 days, 0:00:00
|- USE_X_SENDFILE -> False
|- SERVER_NAME -> None
|- APPLICATION_ROOT -> /
|- SESSION_COOKIE_NAME -> session
|- SESSION_COOKIE_DOMAIN -> None
|- SESSION_COOKIE_PATH -> None
|- SESSION_COOKIE_HTTPONLY -> True
|- SESSION_COOKIE_SECURE -> False
|- SESSION_COOKIE_SAMESITE -> None
...
(truncated output)
To see the filtered configuration keys, we should provide an extra input parameter.
The Custom COMMAND
$ # Filter ouput that matches `database`
$ flask commands cfg database
The OUTPUT
Custom command - Cfg(Filter=database)
|- SQLALCHEMY_DATABASE_URI -> sqlite:///...\flask-command-line-blueprints\db.sqlite3
Let's highlight all configuration parameters with "JSON" in their names:
The Custom COMMAND
$ # Filter ouput that matches `JSON`
$ flask commands cfg JSON
The OUTPUT
Custom command - Cfg(Filter=JSON)
|- JSON_AS_ASCII -> True
|- JSON_SORT_KEYS -> True
|- JSONIFY_PRETTYPRINT_REGULAR -> False
|- JSONIFY_MIMETYPE -> application/json
From this point, the code can be extended with ease to execute other useful tasks:
- delete inactive user accounts
- extract sales information and other useful statistics
- notify users regarding new products and updates
Thanks for reading! For more resource please access:
- Flask CLI (command-line interface) - the official docs
- Use Flask CLI to create commands for your PostgreSQL - blog article
- Flask Starters - a curated index provided by AppSeed
Top comments (3)
Such a great concept and this article is written so well!
Ty Shakar!
This kind of feedback keeps me motivated to write.
You're doing wonderfully; keep on the great work!