[Python] SQLalchemy: changes not committing to db

Discussão em 'Python' iniciado por Stack, Fevereiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to write what should be a relatively simple script using SQLalchemy to interact with a MySQL database. I am pretty new to sqlalchemy, and programming in general, so I am in need of help.

    For some reason, I am not seeing my update queries affecting the database after I run the script. I don't get any errors when I run the script, I simply see no changes in the database. I think I am having a problem with committing the session, but I am not sure how I am going wrong.

    #!/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()

    '''

    Continue reading...

Compartilhe esta Página