pythonflaskflask-script

How can I know the args passed to flask_script's Manager


I have a flask application, in one of its script commands I want to know what's the args passed to the Manager (not the command itself), how can I do that?

$ cat manage.py

#!/usr/bin/env python

from flask import Flask
from flask_script import Manager

app = Flask(__name__)

manager = Manager(app)

manager.add_option("-d", "--debug", dest="debug", action="store_true")

@manager.option('-n', '--name', dest='name', default='joe')
def hello(name):
    # how can I know whether "-d|--debug" is passed in command line
    print("hello", name)

if __name__ == "__main__":
    manager.run()

If I run:

$ python manage.py --debug hello

I want to detect whether '--debug' is passed via command line args within the func of hello. I can't just change

manager.add_option("-d", "--debug", dest="debug", action="store_true")    

to the decorator verion of:

@manager.option('-d', '--debug', action='store_true', dest='debug')
@manager.option('-n', '--name', dest='name', default='joe')
def hello(name, debug=False):

because '-d|--debug' is shared by many commands.


Solution

  • Global options are passed not to command, but to app-creating function.

    See add-option docs.

    For this to work, the manager must be initialized with a factory function rather than a Flask instance. Otherwise any options you set will be ignored.

    So you need to do something like

    app = Flask(__name__)
    
    def init_manager(debug):
        app.debug = debug
        return app
    
    manager = Manager(init_manager)
    

    And then access app.debug