Flask Command-Line - Open-Source Sample
Tags: webdev, flask, python, appseed
Published: 2021-04-08 15:04:08

---
title: Flask Command-Line - Open-Source Sample
published: true
description: The article describes how to add custom commands on top of Flask CLI (command-line interface) - Free sample included.
tags: webdev, flask, python, appseed
---
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](https://appseed.us)**.

---

- [Flask Command-Line](https://github.com/app-generator/flask-command-line-blueprints) - sample project
- [Flask Black Dashboard](https://appseed.us/admin-dashboards/flask-dashboard-black) - the original starter

---

![Flask Command-Line - Sample Project provided by AppSeed.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i8tl0p341t6tucsz8izm.png)

---

**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:

```bash
$ # 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:

```bash
$ # 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:

```bash
$ # 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:

```bash
$ 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](https://github.com/app-generator/flask-command-line-blueprints/blob/master/app/commands.py)" Blueprint:

```python
@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**):

```python
@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**

```bash
$ # Unfiltered output (list all keys)
$ flask commands cfg
```

**The OUTPUT**

```bash
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**

```bash
$ # Filter ouput that matches `database`  
$ flask commands cfg database
```

**The OUTPUT**

```bash
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**

```bash
$ # Filter ouput that matches `JSON`
$ flask commands cfg JSON
```

**The OUTPUT**

```bash
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](https://flask.palletsprojects.com/en/1.1.x/cli/) (command-line interface)   - the official docs
- [Use Flask CLI to create commands for your PostgreSQL](https://itnext.io/use-flask-cli-to-create-commands-for-your-postgresql-on-heroku-in-6-simple-steps-e8166c024c8d) - blog article
- [Flask Starters](https://appseed.us/admin-dashboards/flask) - a curated index provided by [AppSeed](https://appseed.us/)

---

![Flask Starter - Open-Source project provided by AppSeed.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8w9kc5ctl8ht1vrrp8k0.png)