Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-Script How to get to the current app?

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.

like image 882
101010 Avatar asked Dec 11 '22 03:12

101010


1 Answers

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. :-)

like image 131
101010 Avatar answered Dec 29 '22 14:12

101010