How to use flask_cli

Issue

How to use FlaskCLi with flask application in a virtualenv

I created a folder called app and activated the virtualenv and created an app.py file with the following contents

from flask import Flask 
from flask_cli import FlaskCLI

app = Flask('hello')
FlaskCLI(app)

@app.cli.command()
def initdb():
    print ("Creating a database ")

then I used the command export FLASK_APP=app.py and then flask run but got the error

 * Serving Flask app 'hello.py' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
Usage: flask run [OPTIONS]
Try 'flask run --help' for help.

Error: While importing 'hello', an ImportError was raised:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/flask/cli.py", line 256, in locate_app
    __import__(module_name)
  File "/home/kali/Desktop/Hermes/hello.py", line 5, in <module>
    from flask_cli import FlaskCLI
ModuleNotFoundError: No module named 'flask_cli'

this is how i installed the package

pip3 install flask-cli   
Requirement already satisfied: flask-cli in ./lib/python3.9/site-packages (0.4.0)
Requirement already satisfied: click>=2.0 in ./lib/python3.9/site-packages (from flask-cli) (8.0.4)
Requirement already satisfied: Flask>=0.10 in ./lib/python3.9/site-packages (from flask-cli) (2.0.3)
Requirement already satisfied: Jinja2>=3.0 in ./lib/python3.9/site-packages (from Flask>=0.10->flask-cli) (3.0.3)
Requirement already satisfied: itsdangerous>=2.0 in ./lib/python3.9/site-packages (from Flask>=0.10->flask-cli) (2.1.0)
Requirement already satisfied: Werkzeug>=2.0 in ./lib/python3.9/site-packages (from Flask>=0.10->flask-cli) (2.0.3)
Requirement already satisfied: MarkupSafe>=2.0 in ./lib/python3.9/site-packages (from Jinja2>=3.0->Flask>=0.10->flask-cli) (2.1.0)

Solution

The solution is pretty simple. I don’t think you need flask-cli. Try something like the code snippet below, register blueprints, initiate and migrate DB and all sorts of stuff.

from flask.cli import FlaskGroup

app = Flask(__name__)
app.debug = True
cli = FlaskGroup(app)

@app.route('/')
def index():
  return 'Hello World!'

if __name__ == '__main__':
    cli()

Answered By – Abhay

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published