Where should I implement flask custom commands (cli)

前端 未结 3 540
暗喜
暗喜 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

提交回复
热议问题