Accessing User model from Flask shell raises NameError

杀马特。学长 韩版系。学妹 提交于 2019-12-25 07:49:54

问题


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()

回答1:


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,
        }

    ...


来源:https://stackoverflow.com/questions/42005343/accessing-user-model-from-flask-shell-raises-nameerror

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!