YoungJules

Latest and greatest

Nov 7th, 2012
80
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 handling MasterControl Data
  7. # Class is a singleton and takes care of making a connection to the db and creating a cursor
  8. # This is part of a pluggable architecture which simplifies use of different databases and other data sources
  9. # To enable another database in MasterControl (e.g. postgreSQL)
  10. #   Clone MasterControlMySQL.py to MasterControlPostgres.py
  11. #       Adjust imports
  12. #       Adjust database connection params in connect()
  13. #       Adjust SQL statements where required (e.g. postgreSQL may have different syntax for joins...)
  14. #       Remove MasterControlMySQL.py from application path and rerun RFIDServer
  15. # Using other data sources (flat files, excel...)
  16. #   Follow pattern as above and adjust subroutines to get data from other datasource/update other datasource
  17. #   Ensure routines returning a 'row' return an appropriate array of data
  18.  
  19. # Example usage:
  20. #   row = MCData().getMember( '117877', 'FobNumber' )
  21.  
  22. class MCData(object):
  23.     conn = None
  24.     cursor = None
  25.  
  26.     """Use to create a singleton"""
  27.     def __new__(cls, *args, **kwds):
  28.         """
  29.         >>> s = MCData()
  30.         >>> p = MCData()
  31.         >>> id(s) == id(p)
  32.         True
  33.         """
  34.         self = "__self__"
  35.         if not hasattr(cls, self):
  36.             instance = object.__new__(cls)
  37.             instance.init(*args, **kwds)
  38.             setattr(cls, self, instance)
  39.         return getattr(cls, self)
  40.  
  41.     def init(self, *args, **kwds):
  42.         self.connect()
  43.  
  44.     def connect( self ):
  45.         # Information about the database
  46.         database = "ENTS"
  47.         table = "members"
  48.         hostaddr = "localhost"
  49.         username = "mastercontrol"
  50.         # TODO: This is insecure as it can be read by anyone with access to this script, needs to be handled in another way
  51.         password = "pass"
  52.         self.conn = MySQLdb.connect ( host = hostaddr, user = username, passwd = password, db = database, cursorclass=MySQLdb.cursors.DictCursor )
  53.             self.cursor = self.conn.cursor()
  54.         #return conn, cursor
  55.  
  56.     def close( self, conn, cursor ):
  57.         self.cursor.close()
  58.         self.conn.close()
  59.  
  60.     # Go to the database and get the last unlock event for the given door number
  61.     # We match FobNumber on the members table with CardNum on the DoorLog table and search based on door number
  62.     def getLastUnlock( self, doorNum ):
  63.             print "getLastUnlock"
  64.         # We use an inner join because we want to find at least one match on both tables
  65.             self.cursor.execute ("SELECT * from DoorLog inner join members ON members.FobNumber=DoorLog.CardNum where DoorNum = '"+str(doorNum)+"' order by EventDateTime DESC")
  66.             row = self.cursor.fetchone()                 #get the record for the current cardnum
  67.         print "getLastUnlock returning row:"        
  68.         print row
  69.             return row
  70.  
  71.     def getMember( self, fobNumber, fobField ):
  72.         print "getMember"
  73.             self.cursor.execute ("SELECT * from members where "+fobField+" = '" + fobNumber+"'")
  74.             try:
  75.                 row = self.cursor.fetchone()                 #get the record for the current cardnum
  76.             except ValueError:              #Exception:
  77.                     #no match for that user cardNum, send
  78.                     #server.serve_forever()back fail message
  79.                     print "Major Failure \n"
  80.                     #print Exception
  81.         return row
  82.  
  83.     def createDoorLogFail( self, fobNumber, doorNumber, cmd ):
  84.         print "createDoorLogFail"
  85.         self.cursor.execute("insert into DoorLog values ("+fobNumber+
  86.             ",'"+fobNumber+" Not in database: "+cmd+
  87.             "','"+doorNumber+"',now(),NULL)")
  88.  
  89.     def createDoorLogAdmit( self, fobNumber, firstName, lastName, doorNumber):
  90.         print "createDoorLogAdmit"
  91.             self.cursor.execute("insert into DoorLog values ("+fobNumber+
  92.             ",'"+firstName+" "+lastName+" unlocked door "+doorNumber+
  93.             "','"+doorNumber+"',now(),NULL)")
  94.  
  95.     def getSeconds( self, lastUnlock ):
  96.         print "getSeconds"
  97.         self.cursor.execute("select timestampdiff(second,'"+lastUnlock+"',now()) as seconds")
  98.             seconds = self.cursor.fetchone()['seconds']
  99.         if (seconds is None):
  100.             seconds = 2000
  101.         return seconds
  102.  
  103.     def updateMember( self, fobNumber, fobField, lastUnlockField ):
  104.         print "updateMember"
  105.         self.cursor.execute("update members set "+lastUnlockField+" =  now() where "+fobField+" = '"+fobNumber+"'")
Advertisement
Add Comment
Please, Sign In to add comment