gpt4 book ai didi

python - SQLalchemy:更改未提交到数据库

转载 作者:行者123 更新时间:2023-11-29 08:17:13 26 4
gpt4 key购买 nike

我正在尝试使用 SQLalchemy 编写一个相对简单的脚本来与 MySQL 数据库交互。我对 sqlalchemy 和一般编程都很陌生,所以我需要帮助。

由于某种原因,运行脚本后我没有看到更新查询影响数据库。运行脚本时我没有收到任何错误,我只是看到数据库中没有任何更改。我认为我在提交 session 时遇到问题,但我不确定我是怎么出错的。

#!/usr/bin/env python

from sqlalchemy import Column, Integer, String, DateTime, create_engine, update
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime
from IPy import IP
from optparse import OptionParser
from getpass import getpass

#parse the command line options
parser = OptionParser()
parser.add_option('-x', '--expunging', action='store_true', default=False, dest='expunging', help='remove virtual machines that are stuck in expunging state')
parser.add_option('-v', '--volumes', action='store_true', default=False, dest='volumes', help='remove orphaned volumes')
parser.add_option('-n', '--nics', action='store_true', default=False, dest='nics', help='update the ip address and gateway on the nic')
parser.add_option('-d', '--display', action='store_true', default=False, dest='display', help='display the current VMs or volumes ')
(opts, args) = parser.parse_args()


#connect to the database and create some required objects
addr = raw_input('IP address of the MySQL CloudStack database:\n> ')
passwd = getpass('MySQL root passwd:\n> ')
connect_string='mysql://root:'+passwd+'@'+addr+'/cloud'
engine = create_engine(connect_string)
Session = sessionmaker(bind=engine)
Base = declarative_base()
session = Session()


#create the table objects
class cloud_vm(Base):
__tablename__ = 'vm_instance'

id = Column(Integer, primary_key=True)
name = Column(String)
state = Column(String)
removed = Column(DateTime)

def __init__(self, id, name, state, removed):
self.id = id
self.name = name
self.state = state
self.removed = removed

def __repr__(self):
return '%s %s %s %s' % (self.id, self.name, self.state, self.removed)

class cloud_vol(Base):
__tablename__ = 'volumes'

id = Column(Integer, primary_key=True)
name = Column(String)
removed = Column(DateTime)
path = Column(String)

def __init__(self, name, removed, path):
self.name = name
self.removed = removed
self.path = path

def __repr__(self):
return '%s %s %s' % (self.name, self.removed, self.path)

class cloud_networks(Base):
__tablename__ = 'networks'

id = Column(Integer, primary_key=True)
name = Column(String)
cidr = Column(String)
gateway = Column(String)

def __init__(self, name, cidr, gateway):
self.name = name
self.cidr = cidr
self.gateway = gateway

def __repr__(self):
return '%s %s %s' % (self.name, self.cidr, self.gateway)

class cloud_nics(Base):
__tablename__ = 'nics'

id = Column(Integer, primary_key=True)
instance_id = Column(String)
ip4_address = Column(String)
gateway = Column(String)

def __init__(self, state):
self.instance_id = instance_id
self.ip4_address = ip4_address
self.gateway = gateway

def __repr__(self):
return '%s %s %s' % (self.instance_id, self.ip4_address, self.gateway)



#define functions for interacting with the database
def display_current_vm():
for name, state, removed in session.query(cloud_vm.name, cloud_vm.state, cloud_vm.removed).filter(cloud_vm.removed==None):
print name, state

def display_volume_paths():
for name, path in session.query(cloud_vol.name, cloud_vol.path).filter(cloud_vol.removed==None):
print name, '/dev/cskvm-1/'+path

def remove_expunging_vm():
session.query(cloud_vm).filter(cloud_vm.removed==None, cloud_vm.state=='Expunging').update({"removed": datetime.now()})
session.commit()

def remove_orphan_vol(vols): #use a list type for vols
print "Volumes no longer in use:\n"
for i in vols:
for name, path in session.query(cloud_vol.name, cloud_vol.path).filter(cloud_vol.name==i):
print '==> '+name
print '/dev/cskvm-1/'+path
print '\n'
for j in vols:
session.query(cloud_vol).filter(cloud_vol.name==i).update({"removed": datetime.now()})
session.commit()

def update_instance_ip(name, ipaddr, gate):
try:
IP(ipaddr)
IP(gate)
except:
print "not a valid ip address"
for vm_id in session.query(cloud_vm.id).filter(cloud_vm.name==name)[0]:
session.query(cloud_nics).filter(cloud_nics.instance_id==vm_id).update({"ip4_address": ipaddr, "gateway": gate})
session.commit()





update_instance_ip("free-public1","10.1.1.1","10.1.1.1")

'''
#run the main program
def main():
#put program here!

if __name__ == "__main__":
main()

'''

最佳答案

尝试使用

session.flush

来自文档

Flush all the object changes to the database.

http://docs.sqlalchemy.org/en/latest/orm/session.html?highlight=flush#sqlalchemy.orm.session.Session.flush

关于python - SQLalchemy:更改未提交到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20364243/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com