[Python] How do you integrate a flask app and a normal cli group?

Discussão em 'Python' iniciado por Stack, Junho 15, 2025.

  1. Stack

    Stack Membro Participativo

    For example,

    import click

    @click.group()
    @click.option('-x', default='xx', help="set x")
    @click.option('-y', default='yy', help="set y")
    @click.pass_context
    def cli(ctx, **kwargs):
    ctx.obj.update(**kwargs)

    @cli.command()
    @click.pass_context
    def foo(ctx):
    print(ctx.obj['a'])
    print(ctx.obj['b'])

    if __name__ == "__main__":
    cli(obj={'b':'bar'})


    Works, or at least let's assume it does (the next one is cp-pastable). But when I throw flask in the mix:

    import flask
    import click

    app = flask.Flask(__name__)

    @app.cli.group()
    @click.option('-x', default='xx', help="set x")
    @click.option('-y', default='yy', help="set y")
    @click.pass_context
    def cli(ctx, **kwargs):
    ctx.update(**kwargs)

    @cli.command()
    @click.pass_context
    def foo(ctx):
    print(ctx.obj['a'])
    print(ctx.obj['b'])

    if __name__ == "__main__":
    cli(obj={'b':'bar'})


    TypeError: 'ScriptInfo' object is not subscriptable
    ​

    I get a type error, and cannot have both a command line w/ context passing and a flask app defined in the same setup.

    Is there a way to pass items in through the context object and still have everything managed as a flask app?

    Or should I find a work around?

    Continue reading...

Compartilhe esta Página