V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
linuxs
V2EX  ›  Flask

flask 批量导入数据的时候出现错误? 求指教!

  •  
  •   linuxs · 2017-10-26 11:08:56 +08:00 · 2718 次点击
    这是一个创建于 2618 天前的主题,其中的信息可能已经有所发展或是发生改变。
    批量添加数据报错:RuntimeError: application not registered on db instance and no application bound to current context

    from app import create_app,db
    from flask_script import Manager, Shell
    from flask_migrate import Migrate, MigrateCommand
    from script.hosts import hostinfo
    from app.models import Hosts


    app = create_app('default')
    manager = Manager(app)
    migrate = Migrate(app, db)



    def make_shell_context():
    return dict(app=app, db=db, Hosts=Hosts,)

    manager.add_command("shell", Shell(make_context=make_shell_context))
    manager.add_command('db', MigrateCommand)


    hostinfo = hostinfo()
    for i in hostinfo.get_host():
    for info in i:
    info = Hosts(netip=info['PublicIpAddress']['IpAddress'][0],
    name=info['InstanceName'],
    area=info['RegionId'],
    osname=info['OSName'],
    host_config='CPU:%s Mem:%s intout:%s' % (info['Cpu'],info['Memory'],info['InternetMaxBandwidthOut']))
    db.session.add(info)
    db.session.commit()


    if __name__ == '__main__':
    manager.run()
    2 条回复    2017-10-27 07:45:22 +08:00
    linuxs
        1
    linuxs  
    OP
       2017-10-26 11:09:52 +08:00
    hostinfo = hostinfo()
    for i in hostinfo.get_host():
    for info in i:
    info = Hosts(netip=info['PublicIpAddress']['IpAddress'][0],
    name=info['InstanceName'],
    area=info['RegionId'],
    osname=info['OSName'],
    host_config='CPU:%s Mem:%s intout:%s' % (info['Cpu'],info['Memory'],info['InternetMaxBandwidthOut']))
    db.session.add(info)
    db.session.commit() 这段是添加数据的代码
    xlui
        2
    xlui  
       2017-10-27 07:45:22 +08:00 via Android
    按你这样的写法,在 manager.run() 之前就尝试向数据库添加数据。报 no application bound to current context 大概也是这个原因。

    试试看把批量添加数据的操作写成一个命令。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1787 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 16:25 · PVG 00:25 · LAX 08:25 · JFK 11:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.