2

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?

shlomiLan
  • 659
  • 1
  • 9
  • 33

2 Answers2

5

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

Arunmozhi
  • 1,034
  • 8
  • 17
1

In you commands.py you can add register function like that:

def register(app):

    @app.cli.command(name='test_run', help="test_run command")
    def register_test_run():
        test_run()

    # other commands to register

And then in your __init__.py import this register function

from flask import Flask
app = Flask(__name__)

from commands import register
register(app)

Notice, that you should import register after you've initialized your app.