Where should I implement flask custom commands (cli)

前端 未结 3 532
暗喜
暗喜 2020-12-10 14:16

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



        
相关标签:
3条回答
  • 2020-12-10 14:42

    just import it in your app factory

    dir tree
    
    my_app
         L app.py
         L commands.py
    

    commands.py

    @app.cli.command('resetdb')
    def resetdb_command():
        """Here info that will be shown in flask --help"""
        pass
    

    app.py

    def create_app():
        app = Flask(__name__)
        app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
        app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
        db.init_app(app)
    
        with app.app_context():
            from . import routes
            from . import commands  # <----- here
    
            return app
    
    $ export FLASK_APP=my_app/app.py
    $ flask resetdb
    

    but there have to be better way ;) of which I am unaware right now

    0 讨论(0)
  • 2020-12-10 14:43

    I have this layout:

    baseapp.py

    from flask import Flask
    
    app = Flask("CmdAttempt")
    

    app.py

    from .baseapp import app
    
    def main():
        app.run(
            port=5522,
            load_dotenv=True,
            debug=True
        )
    
    if __name__ == '__main__':
        main()
    

    commands.py

    import click
    
    from .baseapp import app
    
    
    @app.cli.command("create-super-user")
    @click.argument("name")
    def create_super_user(name):
        print("Now creating user", name)
    
    
    if __name__ == '__main__':
        from .app import main
        main()
    

    In the console where you run the commands first define the FLASK_APP to be commands.py, then run the commands that you define.

    set FLASK_APP=commands.py
    export FLASK_APP=commands.py
    flask create-super-user me
    

    You can either use a separate terminal for built-in commands or clear the FLASK_APP variable before issuing them. In Linux is even easier because you can do

    FLASK_APP=commands.py flask create-super-user me
    
    0 讨论(0)
  • 2020-12-10 14:47

    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
    
    0 讨论(0)
提交回复
热议问题