Search code examples
pythonflaskflask-cli

Flask CLI command not in __init__.py file


I'm trying to add commands to my Flask app.

This is my __init__.py file:

import os

from flask import Flask
from flask_cors import CORS
from flask_mongoengine import MongoEngine

app = Flask(__name__)
CORS(app)
app.config.from_object(os.environ['APP_SETTINGS'])

db = MongoEngine(app)

import slots_tracker_server.views  # noqa

If I add to it:

@app.cli.command()
def test_run():
    print('here')

I can run flask test_run with no problems, but if I try to move the code to another file, for example: commands.py, I get the error Error: No such command "test_run". when trying to run the command.

What I'm missing?


Solution

  • Use click (the library behind Flask commands) to register your commands:

    # commands.py
    import click
    
    @click.command()
    def test_run():
        print('here')
    

    In your __init__.py import and register the commands:

    # __init__.py
    from yourapp import commands
    
    from flask import Flask
    app = Flask(__name__)
    
    app.cli.add_command(commands.test_run)
    

    Take a look at the official docs