Commits

Mike Driscoll committed dd0268e

Put the database connection in one location and now pass the session object around

  • Participants
  • Parent commits aa6b18d

Comments (0)

Files changed (4)

File InProgress/wxPython and SqlAlchemy Part II/addModRecord.py

     """
 
     #----------------------------------------------------------------------
-    def __init__(self, row=None, title="Add", addRecord=True):
+    def __init__(self, session, row=None, title="Add", addRecord=True):
         """Constructor"""
         wx.Dialog.__init__(self, None, title="%s Record" % title)
+        self.session = session
         self.addRecord = addRecord
         self.selectedRow = row
         if row:
         """
         authorDict, bookDict = self.getData()
         data = ({"author":authorDict, "book":bookDict})
-        controller.addRecord(data)
+        controller.addRecord(self.session, data)
         
         # show dialog upon completion
         commonDlgs.showMessageDlg("Book Added",
         """"""
         authorDict, bookDict = self.getData()
         comboDict = dict(authorDict.items() + bookDict.items())
-        controller.editRecord(self.selectedRow.id, comboDict)
+        controller.editRecord(self.session, self.selectedRow.id, comboDict)
         commonDlgs.showMessageDlg("Book Edited Successfully!", "Success",
                                   wx.ICON_INFORMATION)
         self.Destroy()

File InProgress/wxPython and SqlAlchemy Part II/controller.py

 # controller.py
-from model import Book, Person, OlvBook, metadata
+from model import Book, Person, metadata
 from sqlalchemy import create_engine
 from sqlalchemy.orm import sessionmaker
 
 #----------------------------------------------------------------------
-def addRecord(data):
+def addRecord(session, data):
     """
     Data should be a tuple of two dictionaries in the following format:
     
     author.last_name = data["author"]["last_name"]
     book.person = author
     
-    # connect to session and commit data to database
-    session = connectToDatabase()
+    # commit data to database
     session.add(book)
     session.commit()
     session.close()
     return books
 
 #----------------------------------------------------------------------
-def deleteRecord(idNum):
+def deleteRecord(session, idNum):
     """
     Delete a record from the database
     """
-    session = connectToDatabase()
     record = session.query(Book).filter_by(id=idNum).one()
     session.delete(record)
     session.commit()
     session.close()
     
 #----------------------------------------------------------------------
-def editRecord(idNum, row):
+def editRecord(session, idNum, row):
     """
     Edit a record
     """
-    session = connectToDatabase()
     record = session.query(Book).filter_by(id=idNum).one()
     print
     record.title = row["title"]
     session.close()
 
 #----------------------------------------------------------------------
-def getAllRecords():
+def getAllRecords(session):
     """
     Get all records and return them
     """
-    session = connectToDatabase()
     result = session.query(Book).all()
-    books = convertResults(result)
+##    books = convertResults(result)
     session.close()
-    return books
+    return result
 
 #----------------------------------------------------------------------
-def searchRecords(filterChoice, keyword):
+def searchRecords(session, filterChoice, keyword):
     """
     Searches the database based on the filter chosen and the keyword
     given by the user
     """
-    session = connectToDatabase()
     if filterChoice == "Author":
         qry = session.query(Person)
         result = qry.filter(Person.first_name.contains('%s' % keyword)).all()

File InProgress/wxPython and SqlAlchemy Part II/mediaLocker.py

 import addModRecord
 import commonDlgs
 import controller
+import functools
 import wx
 from ObjectListView import ObjectListView, ColumnDefn
 
 ########################################################################
 class BookPanel(wx.Panel):
     """"""
-
+    
     #----------------------------------------------------------------------
     def __init__(self, parent):
         """Constructor"""
         wx.Panel.__init__(self, parent)
+        self.session = controller.connectToDatabase()
         try:
-            self.bookResults = controller.getAllRecords()
+            self.bookResults = controller.getAllRecords(self.session)
         except:
             self.bookResults = []
         
         self.SetSizer(mainSizer)
         
     #----------------------------------------------------------------------
+    def GetRel(self, data, relation):
+        """Resolve dotted relation entry"""
+        baseAttr = data
+        if not relation == None:
+            comp = relation.split('.')
+            for arel in comp:
+                if baseAttr:
+                    with no_autoflush(wx.GetApp().ds):
+                        baseAttr = getattr(baseAttr, arel)
+        return baseAttr
+    
+    #----------------------------------------------------------------------
+    def GetRelInfo(self, data, relation, colname):
+        """return value or blank"""
+        try:
+            baseAttr = self.GetRel(data, relation)
+ 
+            if baseAttr:
+                with no_autoflush(wx.GetApp().ds):
+                    return getattr(baseAttr, colname)
+            else:
+                return ''
+        except:
+            msg = "Parent: %s, Grand Parent: %s\n" % (self.GetParent(),
+                                                    self.GetGrandParent())
+            msgR = "relation: %s, colname: %s, data: %s\n" % (relation,
+                                                            colname,
+                                                            data)
+            print msg
+            print msgR
+##            logging.error(msg)
+##            logging.exception(msgR)
+        
+    #----------------------------------------------------------------------
     def onAddRecord(self, event):
         """
         Add a record to the database
         """
-        dlg = addModRecord.AddModRecDialog()
+        dlg = addModRecord.AddModRecDialog(self.session)
         dlg.ShowModal()
         dlg.Destroy()
         self.showAllRecords()
         if selectedRow == None:
             commonDlgs.showMessageDlg("No row selected!", "Error")
             return
-        dlg = addModRecord.AddModRecDialog(selectedRow, title="Modify",
+        dlg = addModRecord.AddModRecDialog(self.session, selectedRow,
+                                           title="Modify",
                                            addRecord=False)
         dlg.ShowModal()
         dlg.Destroy()
         if selectedRow == None:
             commonDlgs.showMessageDlg("No row selected!", "Error")
             return
-        controller.deleteRecord(selectedRow.id)
+        controller.deleteRecord(self.session, selectedRow.id)
         self.showAllRecords()
         
     #----------------------------------------------------------------------
         filterChoice = self.categories.GetValue()
         keyword = self.search.GetValue()
         print "%s %s" % (filterChoice, keyword)
-        self.bookResults = controller.searchRecords(filterChoice, keyword)
+        self.bookResults = controller.searchRecords(self.session, 
+                                                    filterChoice, keyword)
         self.setBooks()
         
     #----------------------------------------------------------------------
     #----------------------------------------------------------------------
     def setBooks(self):
         self.bookResultsOlv.SetColumns([
-            ColumnDefn("Title", "left", 350, "title"),
-            ColumnDefn("Author", "left", 150, "author"),
-            ColumnDefn("ISBN", "right", 150, "isbn"),
-            ColumnDefn("Publisher", "left", 150, "publisher")
+            ColumnDefn("Title", "left", 350, valueGetter=functools.partial(self.GetRelInfo, relation="", colname="title")),
+            ColumnDefn("Author", "left", 150, valueGetter=functools.partial(self.GetRelInfo, relation="", colname="author")),
+            ColumnDefn("ISBN", "right", 150,  valueGetter=functools.partial(self.GetRelInfo, relation="", colname="isbn")),
+            ColumnDefn("Publisher", "left", 150, valueGetter=functools.partial(self.GetRelInfo, relation="", colname="publisher"))
         ])
         self.bookResultsOlv.SetObjects(self.bookResults)
         
         """
         Show all records in the object list view control
         """
-        self.bookResults = controller.getAllRecords()
+        self.bookResults = controller.getAllRecords(self.session)
         self.setBooks()
         
 ########################################################################

File InProgress/wxPython and SqlAlchemy Part II/model.py

 DeclarativeBase = declarative_base(engine)
 metadata = DeclarativeBase.metadata
 
-########################################################################
-class OlvBook(object):
-    """
-    Book model for ObjectListView
-    """
-
-    #----------------------------------------------------------------------
-    def __init__(self, id, title, author, isbn, publisher, last_name, first_name):
-        self.id = id  # unique row id from database
-        self.title = title
-        self.author = author
-        self.isbn = isbn
-        self.publisher = publisher
-        self.last_name = last_name
-        self.first_name = first_name
+##########################################################################
+##class OlvBook(object):
+##    """
+##    Book model for ObjectListView
+##    """
+##
+##    #----------------------------------------------------------------------
+##    def __init__(self, id, title, author, isbn, publisher, last_name, first_name):
+##        self.id = id  # unique row id from database
+##        self.title = title
+##        self.author = author
+##        self.isbn = isbn
+##        self.publisher = publisher
+##        self.last_name = last_name
+##        self.first_name = first_name
 
 ########################################################################
 class Person(DeclarativeBase):