Where should I implement flask custom commands (cli)

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

提交回复
热议问题