Flask-Script How to get to the current app?

101010 picture 101010 · Sep 12, 2014 · Viewed 9.3k times · Source

I'm trying to get access to the current app instance from a Flask-Script manager.command.

This errors out (url_map is a property of flask.app)

@manager.command
def my_function():
    x = app.url_map # this fails, because app is a callable
    print "hi"

This works, but I don't like having to add parens next to app.

@manager.command
def my_function():
    x = app().url_map
    print "hi"

The debugger shows that app is a callable. That has to do with the way that I'm creating the app instance. I'm following this pattern:

def create_app(settings=None, app_name=None, blueprints=None):
    ...lots of stuff...
    app = flask.Flask(app_name)
    ...lots of stuff...
    return app


def create_manager(app):
    manager = Manager(app)


    @manager.command
    def my_function():
        x = app.url_map
        print "hi"


def main():
    manager = create_manager(create_app)
    manager.run()


if __name__ == "__main__":
    main()

The docs from flask-script say about the app parameters on Manager(app):

app – Flask instance, or callable returning a Flask instance.

I'm comfortable with putting a callable in there because the docs say it's OK. :-) Plus I've seen others do it like that.

But now I have this peripheral command that I'd like to add and it's forcing me to use the app with parens and that smells wrong. What am I doing wrong?

EDIT: I did some experiments. This is definitely wrong. By adding the parens, the app instance is getting recreated a second time.

Answer

101010 picture 101010 · Sep 12, 2014

Use flask.current_app

This works:

    import flask

... other stuff ...

    @manager.command
    def my_function():
        x = flask.current_app.url_map
        print "hi"

I 'overthunk' it. :-)