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 t…


This content originally appeared on DEV Community and was authored by Sm0ke

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 AppSeed - 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

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


This content originally appeared on DEV Community and was authored by Sm0ke


Print Share Comment Cite Upload Translate Updates
APA

Sm0ke | Sciencx (2021-04-08T15:04:08+00:00) Flask Command-Line – Open-Source Sample. Retrieved from https://www.scien.cx/2021/04/08/flask-command-line-open-source-sample/

MLA
" » Flask Command-Line – Open-Source Sample." Sm0ke | Sciencx - Thursday April 8, 2021, https://www.scien.cx/2021/04/08/flask-command-line-open-source-sample/
HARVARD
Sm0ke | Sciencx Thursday April 8, 2021 » Flask Command-Line – Open-Source Sample., viewed ,<https://www.scien.cx/2021/04/08/flask-command-line-open-source-sample/>
VANCOUVER
Sm0ke | Sciencx - » Flask Command-Line – Open-Source Sample. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/04/08/flask-command-line-open-source-sample/
CHICAGO
" » Flask Command-Line – Open-Source Sample." Sm0ke | Sciencx - Accessed . https://www.scien.cx/2021/04/08/flask-command-line-open-source-sample/
IEEE
" » Flask Command-Line – Open-Source Sample." Sm0ke | Sciencx [Online]. Available: https://www.scien.cx/2021/04/08/flask-command-line-open-source-sample/. [Accessed: ]
rf:citation
» Flask Command-Line – Open-Source Sample | Sm0ke | Sciencx | https://www.scien.cx/2021/04/08/flask-command-line-open-source-sample/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.