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

2017-10-26 11:08:56 +08:00
 linuxs
批量添加数据报错: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()
2719 次点击
所在节点    Flask
2 条回复
linuxs
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
2017-10-27 07:45:22 +08:00
按你这样的写法,在 manager.run() 之前就尝试向数据库添加数据。报 no application bound to current context 大概也是这个原因。

试试看把批量添加数据的操作写成一个命令。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/400875

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX