0

I want to add a user to the database from the Flask shell started by the shell command. I'm using an app factory, so I create my own FlaskGroup cli: python myapp.py shell. When I try to access the User model, I get NameError: name 'User' is not defined. How can I access my models from the Flask shell?

def create_app(config_name):
    application = Flask(__name__)
    application.config.from_object(config[config_name])
    db.init_app(application)

    from user import user
    application.register_blueprint(user, url_prefix='/user')

    return application

def create_cli_app(info):
    return create_app('develop')

@click.group(cls=FlaskGroup, create_app=create_cli_app)
def cli():
    pass

if __name__ == '__main__':
    cli()
davidism
  • 121,510
  • 29
  • 395
  • 339
urbainy
  • 57
  • 1
  • 12

1 Answers1

2

All shell does is launch a shell with your app loaded and an app context pushed. Other than that, it's exactly like any other Python shell by default. You still have to import things if you want to use them, hence the name error.

Use the app.shell_context_processor decorator to inject other things into the shell. Each decorated function returns a dict of names to inject.

def create_app():
    ...

    from myapp.users.models import User

    @app.shell_context_processor
    def inject_models():
        return {
            'User': User,
        }

    ...
davidism
  • 121,510
  • 29
  • 395
  • 339