Connecting Tech Pros Worldwide Help | Site Map

Simple wx.Dialog subclass for Database Login

bartonc's Avatar
Moderator
 
Join Date: Sep 2006
Location: Minden, Nevada, USA
Posts: 6,400
#1   Mar 8 '07
Expand|Select|Wrap|Line Numbers
  1. #Boa:Dialog:DBConnectDialog
  2.  
  3. import wx
  4.  
  5. ##"""Given a set if login specs, create a dbServer instance and
  6. ##   ensure that there is a valid, open connection to the database.
  7. ##   If not, set the dbConnect to None.
  8. ##   spec: dict(UserName=name, Password=pswd, ServerName=host)
  9. ##   Allow names to be set with Default Holder. Consiter Dictionary
  10. ##   or even a tuple? (name, pswd, host)"""
  11.  
  12. import sys
  13. import wxdbtools as db
  14.  
  15.  
  16. def create(parent, loginspec):
  17.     return DBConnectDialog(parent, loginspec)
  18.  
  19. [wxID_DBCONNECTDIALOG, wxID_DBCONNECTDIALOGCANCELBUTTON, wxID_DBCONNECTDIALOGCONNECTBUTTON,
  20.  wxID_DBCONNECTDIALOGOKBUTTON, wxID_DBCONNECTDIALOGPROMPTSTATICTEXT,
  21.  wxID_DBCONNECTDIALOGPWDTEXTCTRL, wxID_DBCONNECTDIALOGREMEMBERCHECKBOX,
  22.  wxID_DBCONNECTDIALOGSERVERNAMETEXTCTRL, wxID_DBCONNECTDIALOGSTATICTEXT1,
  23.  wxID_DBCONNECTDIALOGSTATICTEXT2, wxID_DBCONNECTDIALOGSTATICTEXT3,
  24.  wxID_DBCONNECTDIALOGSTATICTEXT4, wxID_DBCONNECTDIALOGSTATICTEXT6,
  25.  wxID_DBCONNECTDIALOGSTATUSTEXTCTRL, wxID_DBCONNECTDIALOGUSERNAMETEXTCTRL,
  26. ] = [wx.NewId() for _init_ctrls in range(15)]
  27.  
  28. class DBConnectDialog(wx.Dialog):
  29.     def _init_ctrls(self, prnt):
  30.         # generated method, don't edit
  31.         wx.Dialog.__init__(self, id=wxID_DBCONNECTDIALOG, name='DBConnectDialog', parent=prnt,
  32.                 pos=wx.Point(44, 35), size=wx.Size(475, 373),
  33.                 style=wx.STAY_ON_TOP | wx.DIALOG_MODAL | wx.TAB_TRAVERSAL | wx.SUNKEN_BORDER | wx.DEFAULT_DIALOG_STYLE,
  34.                 title='Database Connection Dialog')
  35.         self.SetClientSize(wx.Size(467, 346))
  36.         self.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL, False,'MS Shell Dlg 2'))
  37.         self.SetThemeEnabled(True)
  38.         self.Bind(wx.EVT_CLOSE, self.OnDBConnectDialogClose)
  39.         self.Bind(wx.EVT_ACTIVATE, self.OnDBConnectDialogActivate)
  40.  
  41.         self.staticText1 = wx.StaticText(id=wxID_DBCONNECTDIALOGSTATICTEXT1, label='User Name',
  42.                 name='staticText1', parent=self, pos=wx.Point(16, 40), size=wx.Size(63, 16),
  43.                 style=0)
  44.         self.staticText1.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL, False,
  45.                 'MS Shell Dlg 2'))
  46.  
  47.         self.staticText2 = wx.StaticText(id=wxID_DBCONNECTDIALOGSTATICTEXT2, label='Password',
  48.                 name='staticText2', parent=self, pos=wx.Point(16, 88), size=wx.Size(55, 16),
  49.                 style=0)
  50.  
  51.         self.usernameTextCtrl = wx.TextCtrl(id=wxID_DBCONNECTDIALOGUSERNAMETEXTCTRL,
  52.                 name='usernameTextCtrl', parent=self, pos=wx.Point(16, 56), size=wx.Size(208, 24),
  53.                 style=0, value='')
  54.  
  55.         self.servernameTextCtrl = wx.TextCtrl(id=wxID_DBCONNECTDIALOGSERVERNAMETEXTCTRL,
  56.                 name='servernameTextCtrl', parent=self, pos=wx.Point(240, 56), size=wx.Size(208,
  57.                 24), style=0, value='')
  58.  
  59.         self.staticText3 = wx.StaticText(id=wxID_DBCONNECTDIALOGSTATICTEXT3,
  60.                 label='Server Name or IP Address', name='staticText3', parent=self,
  61.                 pos=wx.Point(240, 40), size=wx.Size(156, 16), style=0)
  62.  
  63.         self.pwdTextCtrl = wx.TextCtrl(id=wxID_DBCONNECTDIALOGPWDTEXTCTRL, name='pwdTextCtrl',
  64.                 parent=self, pos=wx.Point(16, 104), size=wx.Size(168, 24), style=wx.TE_PASSWORD,
  65.                 value='')
  66.  
  67.         self.rememberCheckBox = wx.CheckBox(id=wxID_DBCONNECTDIALOGREMEMBERCHECKBOX,
  68.                 label='Remember Password', name='rememberCheckBox', parent=self, pos=wx.Point(16,
  69.                 136), size=wx.Size(160, 16), style=0)
  70.         self.rememberCheckBox.SetValue(True)
  71.  
  72.         self.staticText4 = wx.StaticText(id=wxID_DBCONNECTDIALOGSTATICTEXT4,
  73.                 label='Connection Status Log', name='staticText4', parent=self, pos=wx.Point(168,
  74.                 160), size=wx.Size(127, 16), style=0)
  75.  
  76.         self.connectButton = wx.Button(id=wxID_DBCONNECTDIALOGCONNECTBUTTON, label='Connect',
  77.                 name='connectButton', parent=self, pos=wx.Point(200, 104), size=wx.Size(74, 26),
  78.                 style=0)
  79.         self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnectButton,
  80.                 id=wxID_DBCONNECTDIALOGCONNECTBUTTON)
  81.  
  82.         self.cancelButton = wx.Button(id=wxID_DBCONNECTDIALOGCANCELBUTTON, label='Cancel',
  83.                 name='cancelButton', parent=self, pos=wx.Point(376, 104), size=wx.Size(74, 26),
  84.                 style=0)
  85.         self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancelButton,
  86.                 id=wxID_DBCONNECTDIALOGCANCELBUTTON)
  87.  
  88.         self.statusTextCtrl = wx.TextCtrl(id=wxID_DBCONNECTDIALOGSTATUSTEXTCTRL,
  89.                 name='statusTextCtrl', parent=self, pos=wx.Point(16, 176), size=wx.Size(432, 160),
  90.                 style=wx.TE_READONLY | wx.TE_MULTILINE, value='')
  91.         self.statusTextCtrl.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL, False,
  92.                 'MS Shell Dlg 2'))
  93.  
  94.         self.staticText6 = wx.StaticText(id=wxID_DBCONNECTDIALOGSTATICTEXT6, label='(NOT SECURE)',
  95.                 name='staticText6', parent=self, pos=wx.Point(16, 152), size=wx.Size(85, 16),
  96.                 style=0)
  97.  
  98.         self.OkButton = wx.Button(id=wxID_DBCONNECTDIALOGOKBUTTON, label='OK', name='OkButton',
  99.                 parent=self, pos=wx.Point(288, 104), size=wx.Size(75, 26), style=0)
  100.         self.OkButton.Bind(wx.EVT_BUTTON, self.OnOkButton, id=wxID_DBCONNECTDIALOGOKBUTTON)
  101.  
  102.         self.promptStaticText = wx.StaticText(id=wxID_DBCONNECTDIALOGPROMPTSTATICTEXT,
  103.                 label='Change your database login:', name='promptStaticText', parent=self,
  104.                 pos=wx.Point(16, 8), size=wx.Size(242, 23), style=0)
  105.         self.promptStaticText.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.NORMAL, False,
  106.                 'MS Shell Dlg 2'))
  107.  
  108.     def __init__(self, parent, defaultHolder):
  109.         self._init_ctrls(parent)
  110.  
  111.         self.EntryDict = {'UserName':self.usernameTextCtrl,
  112.                           'Password':self.pwdTextCtrl,
  113.                           'ServerName':self.servernameTextCtrl}
  114.  
  115.         self.dbServer = db.DBServer(self)   # the sever always has a disply.
  116.         self.dbConnect = None
  117.         self.defaultHolder = defaultHolder
  118.         self.SetWidgetData()
  119.  
  120.     def InitLogin(self):
  121.         user, password, host = self.GetWidgetData()
  122.         self.dbConnect = self.dbServer.Login(host, user, password)
  123.  
  124.     def GetDBServer(self):  # Creator calls here to get the server (may not have a connection)
  125.         return self.dbServer
  126.  
  127.     def IsConnected(self):  # Creator calls here to get the status of the connection
  128.         return self.dbServer.IsOpen(self.dbConnect)
  129.  
  130.     def SetWidgetData(self):
  131.         for var in self.defaultHolder.GetVariables():
  132.             try:
  133.                 self.EntryDict[var['name']].SetValue(var['value'])
  134.             except KeyError:
  135.                 pass
  136.  
  137.     def SetPromptText(self, text):
  138.         self.promptStaticText.SetLabel(text)
  139.  
  140.     def GetWidgetData(self):
  141.         user = self.usernameTextCtrl.GetValue()
  142.         password = self.pwdTextCtrl.GetValue()
  143.         host = self.servernameTextCtrl.GetValue()
  144.         return user, password, host
  145.  
  146.     def write(self, message):
  147.         """Requires a newline at the end of the string."""
  148.         self.statusTextCtrl.AppendText(message)
  149.  
  150.     def ConnectToDB(self, user, password, host, database=""):
  151.         """The dbConnect retains the state returned by the server login()"""
  152.         self.dbConnect = self.dbServer.Login(host, user, password)
  153.         if self.dbConnect:
  154.             if database:
  155.                 self.dbServer.Execute("CREATE DATABASE IF NOT EXISTS %s" % database)
  156.                 self.dbServer.Execute("USE %s" % database)
  157.             self.OkButton.Enable()
  158.             self.OkButton.SetDefault()
  159.             return True
  160.         else:
  161.             wx.Bell()
  162.             self.OkButton.Disable()
  163.             self.usernameTextCtrl.SetSelection(-1, -1)
  164.             self.usernameTextCtrl.SetFocus()
  165.  
  166.     def OnConnectButton(self, event):
  167.         if self.dbServer.IsOpen(self.dbConnect):
  168.             self.dbConnect.close()
  169.  
  170.         user, password, host = self.GetWidgetData()
  171.  
  172.         if self.ConnectToDB(user, password, host):
  173.             self.defaultHolder.SetVariables(UserName=user, Password=password,
  174.                                             ServerName=host)
  175.             self.defaultHolder.UpdateConfig()
  176.  
  177.  
  178.     def OnCancelButton(self, event):
  179.         self.EndModal(wx.ID_CANCEL)
  180.  
  181.     def OnOkButton(self, event):
  182.         self.EndModal(wx.ID_OK)
  183.  
  184.     def OnDBConnectDialogClose(self, event):
  185.         self.EndModal(wx.ID_CLOSE)
  186.  
  187.     def OnDBConnectDialogActivate(self, event):
  188.         """Set the look to be just right on opening."""
  189.         if event.GetActive():
  190.             self.OkButton.Disable()
  191.             self.connectButton.SetDefault()
  192.             pos = self.statusTextCtrl.GetLastPosition()
  193.     #        self.statusTextCtrl.SetInsertionPoint(pos)
  194.             self.statusTextCtrl.ShowPosition(pos)
  195.             self.usernameTextCtrl.SetSelection(-1, -1)
  196.             self.usernameTextCtrl.SetFocus()
  197.         event.Skip()
  198.  
  199.  
  200. if __name__ == "__main__":
  201.     import DefaultHolder as DH
  202.  
  203.     app = wx.PySimpleApp()
  204.     answer = wx.ID_OK
  205.  
  206.     dbDefaultHolder = DH.DefaultValueHolder("HETAP Pro 2.00", "Setup")
  207.     dbDefaultHolder.SetVariables(UserName="barton", Password="1coolSQL",
  208.                                  ServerName="genesis")
  209.     dbDefaultHolder.InitFromConfig()
  210.  
  211.     frame = create(None, dbDefaultHolder)
  212. ##    frame.ShowModal()
  213.  
  214.     while answer == wx.ID_OK:
  215.         frame.ShowModal()
  216.         answer = wx.MessageBox("Do it again?    ", "go again?", wx.OK| wx.CANCEL |wx.ICON_QUESTION, frame)
  217.         print answer, wx.ID_CANCEL
  218. ##        if answer == wx.ID_CANCEL:
  219. ##            break
  220.  
  221.     frame.Destroy()
  222.     app.MainLoop()
  223.  



Reply