updated module to use an internal db wrapper outside the Job() class to allow for cleaner non Job() functions.

This commit is contained in:
Andrew Davidson 2012-08-16 19:22:02 -07:00
parent 70d297054c
commit c2839c0797
2 changed files with 95 additions and 64 deletions

View file

@ -4,12 +4,65 @@
activate_this = "venv/bin/activate_this.py" activate_this = "venv/bin/activate_this.py"
execfile(activate_this, dict(__file__=activate_this)) execfile(activate_this, dict(__file__=activate_this))
######
### What are we going to be using?
######
import os import os
import time import time
import uuid import uuid
from subprocess import call from subprocess import call
import sqlite3 import sqlite3
######
### Classes!
#####
class _db:
def _connect(self, db="jobs.db"):
""" connect()
connects to the sqlite database, uses a try/except to return False if it fails
"""
try:
self._conn = sqlite3.connect('jobs.db')
self._c = self._conn.cursor()
return True
except:
return False
def commit(self):
return self._conn.commit()
def query(self,query,returns="list",timeout=10,db="jobs.db"):
""" query()
run a query against the sqlite database. will attempt to reconnect if necessary.
will timeout after $timeout seconds.
"""
t = time.time() + timeout
while True:
try:
self._c.execute(query)
break
except:
if db != "jobs.db":
self._connect(db=db)
else:
if not self._connect():
print "ERROR: Cannot connect to database."
time.sleep(2)
if time.time() > t:
print 'ERROR: Query timed out.'
break
if returns == "list":
return self._c.fetchall()
elif returns == "one":
return self._c.fetchone()
# Job Class # Job Class
class Job: class Job:
def __init__(self, due = time.time() + 3600, command = 'true', originator = 'indenture', def __init__(self, due = time.time() + 3600, command = 'true', originator = 'indenture',
@ -21,16 +74,6 @@ class Job:
self.originator = originator self.originator = originator
self.completed = completed self.completed = completed
def _connect(self, db="jobs.db"):
""" _connect()
connects to the sqlite database, uses a try/except to return False if it fails
"""
try:
self._conn = sqlite3.connect('jobs.db')
self._c = self._conn.cursor()
return True
except:
return False
def _full_exec(self): def _full_exec(self):
""" _full_exec() """ _full_exec()
@ -38,33 +81,6 @@ class Job:
""" """
return self.command+' '+self.arguments return self.command+' '+self.arguments
def _query(self,query,returns="list",timeout=10,db="jobs.db"):
""" _query()
run a query against the sqlite database. will attempt to reconnect if necessary.
will timeout after $timeout seconds.
"""
t = time.time() + timeout
while True:
try:
self._c.execute(query)
break
except:
if db != "jobs.db":
self.connect(db=db)
else:
self._connect()
time.sleep(2)
if time.time() > t:
print 'ERROR: Query timed out.'
break
if returns == "list":
return self._c.fetchall()
elif returns == "one":
return self._c.fetchone()
def _disconnect(self): def _disconnect(self):
""" _disconnect() """ _disconnect()
@ -97,26 +113,16 @@ class Job:
""" """
return call(self.full_exec().split()) return call(self.full_exec().split())
def list_jobs(self, include_completed=False):
""" list_jobs(include_completed = False)
list all the jobs that need to be done, does not include completed
jobs by default.
"""
query = 'SELECT * FROM jobs'
if include_completed == False:
query += ' WHERE `completed` = 0'
query += ';'
for row in self._query(query):
print row
def open(self, uuid): def open(self, uuid):
""" open() """ open()
runs a query to populate with the information of an existing job runs a query to populate with the information of an existing job
in the database in the database
""" """
data = self._query('SELECT uuid,command,arguments,due,originator,completed FROM jobs WHERE uuid = "' + uuid + '" LIMIT 1;', returns="one")
jobsdb = _db()
data = jobsdb.query('SELECT uuid,command,arguments,due,originator,completed FROM jobs WHERE uuid = "' + uuid + '" LIMIT 1;', returns="one")
print data print data
if data: if data:
(self.uuid, self.command, self.arguments, self.due, self.originator, self.completed) = data (self.uuid, self.command, self.arguments, self.due, self.originator, self.completed) = data
@ -127,11 +133,11 @@ class Job:
saves the current job to the database. will determine if it's saves the current job to the database. will determine if it's
necessary insert a new job or update an old job. necessary insert a new job or update an old job.
""" """
print 'Does this ID exist?'
jobsdb = _db()
test = 'SELECT uuid FROM jobs WHERE uuid = "' + str(self.uuid) + '";' test = 'SELECT uuid FROM jobs WHERE uuid = "' + str(self.uuid) + '";'
print test if jobsdb.query(test):
if self._query(test):
print 'Yes.'
query = 'UPDATE jobs SET ' query = 'UPDATE jobs SET '
query += 'uuid = "' + str(self.uuid) + '", ' query += 'uuid = "' + str(self.uuid) + '", '
query += 'command = "' + self.command + '", ' query += 'command = "' + self.command + '", '
@ -143,10 +149,9 @@ class Job:
else: else:
query += 'completed = 0' query += 'completed = 0'
query += ';' query += ';'
print self._query(query) jobsdb.query(query)
self._conn.commit() jobsdb.commit()
else: else:
print 'No.'
query = 'INSERT INTO jobs (uuid, command, arguments, due, originator, completed) ' query = 'INSERT INTO jobs (uuid, command, arguments, due, originator, completed) '
query += 'VALUES (' query += 'VALUES ('
query += '"' + str(self.uuid) + '",' query += '"' + str(self.uuid) + '",'
@ -159,10 +164,8 @@ class Job:
else: else:
query += str(0) query += str(0)
query += ');' query += ');'
print 'Executing: ' jobsdb.query(query)
print query jobsdb.commit()
self._query(query)
self._conn.commit()
def what_time(self): def what_time(self):
""" what_time() """ what_time()
@ -178,7 +181,9 @@ class Job:
return self._full_exec() return self._full_exec()
######
### Helper Functions
######
def pretty_date(time=False): def pretty_date(time=False):
@ -252,3 +257,29 @@ def pretty_date(time=False):
if day_diff < 365: if day_diff < 365:
return str(day_diff/30) + " months from now" return str(day_diff/30) + " months from now"
return str(day_diff/365) + " years from now" return str(day_diff/365) + " years from now"
######
### General functions
######
def list_jobs(include_completed=False):
""" list_jobs(include_completed = False)
list all the jobs that need to be done, does not include completed
jobs by default.
"""
query = 'SELECT * FROM jobs'
if include_completed == False:
query += ' WHERE `completed` = 0'
query += ';'
jobsdb = _db()
for row in jobsdb.query(query):
print row

View file

@ -11,7 +11,7 @@ print 'Create new instance'
j = indenture.Job() j = indenture.Job()
print 'List jobs' print 'List jobs'
j.list_jobs() indenture.list_jobs()
print 'Open job' print 'Open job'
j.open(uuid="amd1") j.open(uuid="amd1")