我应该在哪里实现flask自定义命令(CLI) [英] Where should I implement flask custom commands (cli)

查看:404
本文介绍了我应该在哪里实现flask自定义命令(CLI)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在flask中创建自定义命令需要访问该应用,该应用通常是在app.py中创建的,如下所示:

 import click
from flask import Flask

app = Flask(__name__)

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

但是,为了不让我的app.py肿,我想将自定义命令放在单独的文件中,例如commands.py,但这不起作用,因为我项目的入口点是app.py,因此我必须在commands.py中导入app,并在app.py中导入命令,这会导致循环导入错误./p>

如何在单独的文件中创建自定义命令?

解决方案

实现此目标的一种方法是使用 from flask import Flask from commands import usersbp app = Flask(__name__) # you MUST register the blueprint app.register_blueprint(usersbp)

==>命令.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))
 

执行flask users后,您将收到如下响应:

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

Options:
  --help  Show this message and exit.

Commands:
  create  Creates a user
 

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 ?

解决方案

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

这篇关于我应该在哪里实现flask自定义命令(CLI)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆