mardi 23 février 2016

String/Int Manipulation with CLI and DB Integration

I'm trying to get a value from a DB, convert it to a string and pass it to a CLI command. Then once that works, flip a bit in that same DB to 'register' that rows status. I'm not a developer by any means so there are a LOT of hacks here. I can get the value out of the DB during the first c.execute and pass it to the 'vmcmd' section but getting that value back into the DB with the second c.execute is failing due to the tuple formatting. Any ideas? Thanks.

#!/usr/bin/python
import sqlite3
import sys, getopt, string, subprocess
from lxml import etree
import os
#Script queries DB, gets a hostname and flips status bit.

sqlite_file = '/tmp/hostnames.db'
table_name = 'hostnamepool'
id_column = 'id'
column_name = 'name'
column_name2 = 'status'

conn = sqlite3.connect(sqlite_file, timeout=5.0)
conn.text_factory = str


#pass vmid from VM_HOOK - RUNNING
for arg in sys.argv:
  vmid = arg



def main():
  #Open our connection
  c = conn.cursor()

  #Grab a row at random. Pass it to rowoutput for sanitizing

  try:
    c.execute("SELECT name FROM '{tn}' WHERE status != '1' ORDER BY RANDOM() LIMIT 1".\
      format(cn=column_name, tn=table_name))
  except sqlite3.IntegrityError:
    print('ERROR: ID already exists in PRIMARY KEY column {}'.format(id_column))

  rowoutput = c.fetchall()

  conn.commit()
  print rowoutput[1]

  stringput = str(rowoutput)

  stripped = stringput.strip("'[()],'")

  strippedappend = 'tat'+str(stripped)


  vmcmd = "onevm rename %s %s"%(vmid,strippedappend)
  os.system(vmcmd)

  c.execute("UPDATE hostnamepool SET status='1' WHERE name =(?)", (stripped,))

  print strippedsql
  #print (rowoutput)
  #print vmid
  return stripped

  conn.commit()
  conn.close() 

if __name__ == "__main__":
    #main(sys.argv[1:])
  x = main()  
  #print( x )

Aucun commentaire:

Enregistrer un commentaire