DEV Community

Sm0ke
Sm0ke

Posted on • Edited on • Originally published at blog.appseed.us

Flask Command-Line - Open-Source Sample

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 provided by AppSeed.


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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

The "Commands" node shows two commands that we can invoke and check the results:

$ flask commands hello
Custom command - Hello               <- The Output 
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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 )
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

The OUTPUT

Custom command - Cfg(Filter=database)
  |- SQLALCHEMY_DATABASE_URI -> sqlite:///...\flask-command-line-blueprints\db.sqlite3
Enter fullscreen mode Exit fullscreen mode

Let's highlight all configuration parameters with "JSON" in their names:

The Custom COMMAND

$ # Filter ouput that matches `JSON`
$ flask commands cfg JSON
Enter fullscreen mode Exit fullscreen mode

The OUTPUT

Custom command - Cfg(Filter=JSON)
  |- JSON_AS_ASCII -> True
  |- JSON_SORT_KEYS -> True
  |- JSONIFY_PRETTYPRINT_REGULAR -> False
  |- JSONIFY_MIMETYPE -> application/json
Enter fullscreen mode Exit fullscreen mode

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 Starter - Open-Source project provided by AppSeed.

Top comments (3)

Collapse
 
polakshahar profile image
Shahar Polak

Such a great concept and this article is written so well!

Collapse
 
sm0ke profile image
Sm0ke

Ty Shakar!
This kind of feedback keeps me motivated to write.

Collapse
 
polakshahar profile image
Shahar Polak

You're doing wonderfully; keep on the great work!