Where should I implement flask custom commands (cli)

瘦欲@ 提交于 2019-12-24 01:01:40

问题


Creating custom commands in flask needs access to the app, which is generally created in app.py like this:

import click
from flask import Flask

app = Flask(__name__)

@app.cli.command("create-user")
@click.argument("name")
def create_user(name):
    ...

However, in order not to bloat my app.py, I want to put my custom commands in a separate file e.g. commands.py, but this doesn't work because the entrypoint to my project is app.py, so I'll have to import app in commands.pyand import my commands in app.py which results in a circular import error.

How can I create custom commands in separate files ?


回答1:


One way to achieve this would be using blueprints

I have tested it using Flask 1.1.1, so be sure to check the documentation of the correct version that you have.

Here is the general idea:

  1. Create one or more Blueprints in a different file, let's say it's called commands.py
  2. Then import the new blueprints and register them to your app

==> app.py <==

from flask import Flask
from commands import usersbp

app = Flask(__name__)
# you MUST register the blueprint
app.register_blueprint(usersbp)

==> commands.py <==

import click
from flask import Blueprint

usersbp = Blueprint('users', __name__)

@usersbp.cli.command('create')
@click.argument('name')
def create(name):
    """ Creates a user """
    print("Create user: {}".format(name))

Upon executing flask users you should get a response like the following:

flask users
Usage: flask users [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  create  Creates a user


来源:https://stackoverflow.com/questions/57202736/where-should-i-implement-flask-custom-commands-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!