YoungJules

Class/Singleton version

Nov 7th, 2012
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python
  2.  
  3. import MySQLdb
  4. import MySQLdb.cursors
  5.  
  6. class MCDataSource(object):
  7.     # Information about the database      
  8.  
  9.     database = "ENTS"
  10.     table = "members"
  11.     hostaddr = "localhost"
  12.     username = "mastercontrol"
  13.     # TODO: This is insecure as it can be read by anyone with access to this script, needs to be handled in another way
  14.     password = "pass"
  15.     conn = None
  16.     cursor = None
  17.  
  18.     """Use to create a singleton"""
  19.     def __new__(cls, *args, **kwds):
  20.         """
  21.         >>> s = Singleton()
  22.         >>> p = Singleton()
  23.         >>> id(s) == id(p)
  24.         True
  25.         """
  26.         self = "__self__"
  27.         if not hasattr(cls, self):
  28.             instance = object.__new__(cls)
  29.             instance.init(*args, **kwds)
  30.             setattr(cls, self, instance)
  31.         return getattr(cls, self)
  32.  
  33.     def init(self, *args, **kwds):
  34.         connect()
  35.  
  36.     def connect():
  37.         self.conn = MySQLdb.connect ( host = hostaddr, user = username, passwd = password, db = database, cursorclass=MySQLdb.cursors.DictCursor )
  38.             self.cursor = conn.cursor()
  39.         #return conn, cursor
  40.  
  41.     def close(conn, cursor):
  42.         self.cursor.close()
  43.         self.conn.close()
  44.  
  45.     # Go to the database and get the last unlock event for the given door number
  46.     # We match FobNumber on the members table with CardNum on the DoorLog table and search based on door number
  47.     def getLastUnlock( doorNum ):
  48.             print "getLastUnlock connecting to db"
  49.         #conn, cursor = connect()
  50.             #conn = MySQLdb.connect ( host = hostaddr, user = username, passwd = password, db = database, cursorclass=MySQLdb.cursors.DictCursor )
  51.             #cursor = conn.cursor()                          #connect to users db    
  52.             print "connection cursor created"
  53.         # We use an inner join because we want to find at least one match on both tables
  54.             self.cursor.execute ("SELECT * from DoorLog inner join members ON members.FobNumber=DoorLog.CardNum where DoorNum = '"+str(doorNum)+"' order by EventDateTime DESC")
  55.             row = self.cursor.fetchone()                 #get the record for the current cardnum
  56.         print "getLastUnlock returning row:"        
  57.         print row
  58.         #close(conn, cursor)
  59.             return row
  60.  
  61.  
  62.     def getMember( fobNumber, fobField ):
  63.             #conn = MySQLdb.connect ( host = hostaddr, user = username, passwd = password, db = database, cursorclass=MySQLdb.cursors.DictCursor )
  64.             #cursor = conn.cursor()                          #connect to users db    
  65.         print "getMember connecting to db"
  66.         #conn, cursor = connect()
  67.             self.cursor.execute ("SELECT * from members where "+fobField+" = '" + fobNumber+"'")
  68.  
  69.             try:
  70.                 row = self.cursor.fetchone()                 #get the record for the current cardnum
  71.             except ValueError:              #Exception:
  72.                     #no match for that user cardNum, send
  73.                     #server.serve_forever()back fail message
  74.                     print "Major Failure \n"
  75.                     #print Exception
  76.  
  77.             #close the mysql connection            
  78.             #close(conn, cursor)
  79.         return row
  80.  
  81.     def createDoorLogFail( fobNumber, doorNumber, cmd ):
  82.         print "createDoorLogFail connecting to db"
  83.         #conn, cursor = connect()
  84.         self.cursor.execute("insert into DoorLog values ("+fobNumber+
  85.             ",'"+fobNumber+" Not in database: "+cmd+
  86.             "','"+doorNumber+"',now(),NULL)")
  87.         #close(conn, cursor)
  88.  
  89.     def createDoorLogAdmit( fobNumber, firstName, lastName, doorNumber):
  90.         print "createDoorLogAdmit connecting to db"
  91.         #conn, cursor = connect()
  92.             self.cursor.execute("insert into DoorLog values ("+fobNumber+
  93.             ",'"+firstName+" "+lastName+" unlocked door "+doorNumber+
  94.             "','"+doorNumber+"',now(),NULL)")
  95.         #close(conn, cursor)
  96.  
  97.     def getSeconds( lastUnlock ):
  98.         print "getSeconds connecting to db"
  99.         #conn, cursor = connect()
  100.         self.cursor.execute("select timestampdiff(second,'"+lastUnlock+"',now()) as seconds")
  101.             seconds = self.cursor.fetchone()['seconds']
  102.         if (seconds is None):
  103.             seconds = 2000
  104.         #close(conn, cursor)
  105.         return seconds
  106.  
  107.     def updateMember( fobNumber, fobField, lastUnlockField ):
  108.         print "updateMember connecting to db"
  109.         #conn, cursor = connect()
  110.         self.cursor.execute("update members set "+lastUnlockField+" =  now() where "+fobField+" = '"+fobNumber+"'")                                    
  111.         #close(conn, cursor)
Advertisement
Add Comment
Please, Sign In to add comment