从Flask Shell访问用户模型会引发NameError [英] Accessing User model from Flask shell raises NameError

查看:273
本文介绍了从Flask Shell访问用户模型会引发NameError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 shell 命令开始的Flask Shell中向数据库添加用户。我正在使用应用程序工厂,因此创建了自己的 FlaskGroup cli: python myapp.py shell 。当我尝试访问 User 模型时,出现 NameError:名称'User'未定义。如何从Flask外壳访问模型?

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


推荐答案

所有 shell 所做的是启动一个加载了您的应用程序并推送了应用程序上下文的外壳程序。除此之外,它默认情况下与其他任何Python shell一样。如果要使用它们,仍然必须导入东西,因此会出现名称错误。

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.

使用 app.shell_context_processor 装饰器可将其他内容注入到外壳中。每个修饰的函数都返回要插入名称的字典。

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

    ...

这篇关于从Flask Shell访问用户模型会引发NameError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆