473,326 Members | 2,114 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Default Values and Config File Class using wxPyton and dictionaries

bartonc
6,596 Expert 4TB
For those of you who have never used the *listofargs and **dictofargs syntax, here is a look at the latter. By using **kwargs, a dictionary of any size is sent into the fuction as dict(a=1, b=2). Inside the function, it's just a dictionary named kwargs (or whaterver, but this is conventional). The truly amazing thing to me is that I am able to write to the Windows registry with so little interface!

Expand|Select|Wrap|Line Numbers
  1. """Encapuslate a Default Values Object and Config File"""
  2.  
  3. from inspect import getmembers
  4. import wx
  5.  
  6. class DefaultValueHolder(object):
  7.     """Intended for use with wxConfig (or maybe _winreg) to set up and/or get
  8.        registry key names and values. Name attrs as default*. "default"
  9.        will be stripped of when reading and writing to the config file"""
  10. ##    defaultTestStr = "this is a test"
  11. ##    defaultTestInt = 1
  12.  
  13.     def __init__(self, appName, grpName):
  14.         """The name of the config file that will be created"""
  15.         self.appName = appName          # if the key doesn't exit, it will be created
  16.         self.grpName = grpName          # same goes for groups.
  17.         self.config = wx.Config(appName) # Open the file (HKCU in windows registry)
  18.  
  19.     def GetVariables(self):
  20.         return [{"name":var[0][7:], "value":var[1], "type":type(var[1])}
  21.                 for var in getmembers(self) if var[0].startswith('default')]
  22.  
  23.     def SetVariables(self, **kwargs):
  24.         for name, value in kwargs.items():
  25.             setattr(self, "default" + name, value)
  26.  
  27.     def InitFromConfig(self):
  28.         self.config.SetPath(self.grpName)
  29.         for var in self.GetVariables():
  30.             if var['type'] == str:
  31.                 self.config.Write(var['name'], var['value'])
  32.             elif var['type'] == int:
  33.                 self.config.WriteInt(var['name'], var['value'])
  34.             elif var['type'] == float:
  35.                 self.config.WriteFloat(var['name'], var['value'])
  36.  
  37.  
  38. if __name__ == "__main__":
  39.     test = DefaultValueHolder("MyAppName", "Database")
  40.  
  41.     test.SetVariables(UserName = "joe", Password = "", ServerName = "MyServer")
  42.     #### this also works:
  43.     ## test.defaultUserName = "joe"
  44.  
  45.     test.InitFromConfig()
Dec 9 '06 #1
12 2618
bartonc
6,596 Expert 4TB
Ok- it was a little more complicated that I initially thought, but not much.
Here's the final version. GetVariables() uses a "list comprehension" to return a list of dictionaries. comprehensions are nifty little list builders which avoid list.append() calls if you don't have lots of stuff going on in your loop. Sometimes, loops with append() are called for, however. Generators look a lot like comprehensions but don't actually make the list in memory until you assign it something ie:
a, b = (i for i in range(2))
also very handy.

Expand|Select|Wrap|Line Numbers
  1. """Encapuslate a Default Values Object and Config File"""
  2.  
  3. from inspect import getmembers
  4. import wx
  5.  
  6. class DefaultValueHolder(object):
  7.     """Intended for use with wxConfig (or maybe _winreg) to set up and/or get
  8.        registry key names and values. Name attrs as default*. "default"
  9.        will be stripped of when reading and writing to the config file"""
  10.  
  11.     def __init__(self, appName, grpName):
  12.         """Open or create the application key"""
  13.         self.grpName = grpName  # if the key or group doesn't exit, it will be created
  14.         self.config = wx.Config(appName)     # Open the file (HKCU in windows registry)
  15.  
  16.     def GetVariables(self):
  17.         return [{"name":var[0][7:], "value":var[1], "type":type(var[1])}
  18.                 for var in getmembers(self) if var[0].startswith('default')]
  19.  
  20.     def SetVariables(self, varDict={}, **kwargs):
  21.         kwargs.update(varDict)
  22.         for name, value in kwargs.items():
  23.             setattr(self, "default" + name, value)
  24.  
  25.     def InitFromConfig(self):
  26.         config = self.config
  27.         group = self.grpName
  28.  
  29.         if not config.Exists(group):
  30.             self.WriteRegistryGroup(Group)
  31.             return
  32.  
  33.         config.SetPath(group)
  34.         for var in self.GetVariables():
  35.             name = var['name']
  36.             print name, "exists"
  37.             if config.Exists(name):
  38.                 value = self.ReadRegistry(name, var['type'])
  39.                 self.SetVariables({name:value})
  40.             else:
  41.                 self.WriteRegistry(name, var['value'], var['type'])
  42.         config.SetPath("")
  43.  
  44.     def UpdateConfig(self):
  45.         self.WriteRegistryGroup(self.grpName)
  46.  
  47.     def WriteRegistryGroup(self, group):
  48.         self.config.SetPath(group)
  49.         for var in self.GetVariables():
  50.             self.WriteRegistry(var['name'], var['value'], var['type'])
  51.         self.config.SetPath("")
  52.  
  53.     def ReadRegistry(self, name, type):
  54.         value = None
  55.         if type == str:
  56.             value = self.config.Read(name)
  57.         elif type in (int, long):
  58.             value = self.config.ReadInt(name)
  59.         elif type == float:
  60.             value = self.config.ReadFloat(name)
  61.         return value
  62.  
  63.     def WriteRegistry(self, name, value, type):
  64.         print "writing registry", name, value, type
  65.         if type == str:
  66.             self.config.Write(name, value)
  67.         elif type in (int, long):
  68.             self.config.WriteInt(name, value)
  69.         elif type == float:
  70.             self.config.WriteFloat(name, value)
  71.  
  72.  
  73. if __name__ == "__main__":
  74.     test = DefaultValueHolder("HETAP Pro 2.00", "Database")
  75.     test.SetVariables(UserName = "barton", Password = "", ServerName = "MyServer", database="trails")
  76.     test.InitFromConfig()
  77.     print test.GetVariables()
  78.  
  79. ##    #### this also works:
  80. ##    ## test.defaultUserName = "joe"
  81. ##
Dec 10 '06 #2
bvdet
2,851 Expert Mod 2GB
Good AM Barton! Thanks for sharing this code. It looks nicely structured and well thought out. I have one question though. Where/how is the below method and its argument defined?
Expand|Select|Wrap|Line Numbers
  1.         if not config.Exists(group):
  2.             self.WriteRegistryGroup(Group)
  3.             return
Thanks again Barton. Learning about new things is always interesting if not fun!
Dec 10 '06 #3
bartonc
6,596 Expert 4TB
Good AM Barton! Thanks for sharing this code. It looks nicely structured and well thought out. I have one question though. Where/how is the below method and its argument defined?
Expand|Select|Wrap|Line Numbers
  1.         if not config.Exists(group):
  2.             self.WriteRegistryGroup(Group)
  3.             return
Thanks again Barton. Learning about new things is always interesting if not fun!
Hay! This system works! Fresh eyes see bugs! Since those entries do exist, on my system (not on a fresh installation) that call never got made, so I never got an errror. Thanks, BV. I have edited the original.
Dec 10 '06 #4
bvdet
2,851 Expert Mod 2GB
Hay! This system works! Fresh eyes see bugs! Since those entries do exist, on my system (not on a fresh installation) that call never got made, so I never got an errror. Thanks, BV. I have edited the original.
You were just testing us, weren't you Barton? :)
Dec 11 '06 #5
bartonc
6,596 Expert 4TB
You were just testing us, weren't you Barton? :)
THIS is the test: It didn't actually work! I Fixed it though... three lines:

Expand|Select|Wrap|Line Numbers
  1.     def SetVariables(self, varDict={}, **kwargs):
  2.         kwargs.update(varDict)
  3.  
  4.  
  5. # in InitFromConfig...
  6.                 self.SetVariables({name:value})
Dec 11 '06 #6
THIS is the test: It didn't actually work! I Fixed it though... three lines:

Expand|Select|Wrap|Line Numbers
  1.     def SetVariables(self, varDict={}, **kwargs):
  2.         kwargs.update(varDict)
  3.  
  4.  
  5. # in InitFromConfig...
  6.                 self.SetVariables({name:value})
Barton,

I'm a little unsteady about this last patch...

In 'InitFromConfig", does "self.SetVariables(...)" replace "self.WriteRegistryGroup(Group)"?

Trying to store the final final away for future reference. :)

Thanks.
Dec 16 '06 #7
bartonc
6,596 Expert 4TB
Here it is in it's entirety. Sorry about the confussion.

Expand|Select|Wrap|Line Numbers
  1. """Encapuslate a Default Values Object and Config File"""
  2.  
  3. from inspect import getmembers
  4. import wx
  5.  
  6. class DefaultValueHolder(object):
  7.     """Intended for use with wxConfig (or maybe _winreg) to set up and/or get
  8.        registry key names and values. Name attrs as default*. "default"
  9.        will be stripped of when reading and writing to the config file.
  10.        You may not use the name varDict as one of the variable names."""
  11.  
  12.     def __init__(self, appName, grpName):
  13.         """Open or create the application key"""
  14.         self.appName = appName
  15.         self.grpName = grpName  # if the key or group doesn't exit, it will be created
  16.         self.config = wx.Config(appName)     # Open the file (HKCU in windows registry)
  17.  
  18.     def GetVariables(self):
  19.         return [{"name":var[0][7:], "value":var[1], "type":type(var[1])}
  20.                 for var in getmembers(self) if var[0].startswith('default')]
  21.  
  22.     def SetVariables(self, varDict={}, **kwargs):
  23.         kwargs.update(varDict)
  24.         for name, value in kwargs.items():
  25.             setattr(self, ("default" + name), value)
  26.  
  27.     def InitFromConfig(self):
  28.         config = self.config
  29.         group = self.grpName
  30.  
  31.         if not config.Exists(group):
  32.             self.WriteRegistryGroup(group)
  33.  
  34.         else:
  35.             config.SetPath(group)
  36.             for var in self.GetVariables():
  37.                 name = var['name']
  38.                 if config.Exists(name):
  39.                     value = self.ReadRegistry(name, var['type'])
  40.                     self.SetVariables({name:value})
  41.                 else:
  42.                     self.WriteRegistry(name, var['value'], var['type'])
  43.         config.SetPath("")
  44.  
  45.     def WriteRegistryGroup(self, group):
  46.         self.config.SetPath(group)
  47.         for var in self.GetVariables():
  48.             self.WriteRegistry(var['name'], var['value'], var['type'])
  49.         self.config.SetPath("")
  50.  
  51.     def UpdateConfig(self):
  52.         self.WriteRegistryGroup(self.grpName)
  53.  
  54.     def ReadRegistry(self, name, type):
  55.         value = None
  56.         if type == str:
  57.             value = self.config.Read(name)
  58.         elif type in (int, long):
  59.             value = self.config.ReadInt(name)
  60.         elif type == float:
  61.             value = self.config.ReadFloat(name)
  62.         return value
  63.  
  64.     def WriteRegistry(self, name, value, type):
  65.         if type == str:
  66.             self.config.Write(name, value)
  67.         elif type in (int, long):
  68.             self.config.WriteInt(name, value)
  69.         elif type == float:
  70.             self.config.WriteFloat(name, value)
  71.  
  72.  
  73. if __name__ == "__main__":
  74.     test = DefaultValueHolder("HETAP Pro 2.00", "Database")
  75.     test.SetVariables(UserName = "peter", Password = "pan", ServerName = "MyServer", database="")
  76.     test.InitFromConfig()
  77.     for line in test.GetVariables():
  78.         print line
  79.  
  80. ##    #### this also works:
  81. ##    ## test.defaultUserName = "joe"
  82. ##
  83.  
Dec 17 '06 #8
Here it is in it's entirety. Sorry about the confussion.

Expand|Select|Wrap|Line Numbers
  1. """Encapuslate a Default Values Object and Config File"""
  2.  
  3. ...
  4.  
  5.     def InitFromConfig(self):
  6.         config = self.config
  7.         group = self.grpName
  8.  
  9.         if not config.Exists(group):
  10.             self.WriteRegistryGroup(Group)
  11.             return
  12.  
  13.  
Well, almost:

Expand|Select|Wrap|Line Numbers
  1.         if not config.Exists(group):
  2.             self.WriteRegistryGroup(group)  #  <<=== lowercase
  3.             return
  4.  
:)

Cheers,

- Mark
Dec 17 '06 #9
bartonc
6,596 Expert 4TB
Well, almost:

Expand|Select|Wrap|Line Numbers
  1.         if not config.Exists(group):
  2.             self.WriteRegistryGroup(group)  #  <<=== lowercase
  3.             return
  4.  
:)

Cheers,

- Mark
Do you realize that you just saved me much embarrassment? This is due to be installed on a system that would certainly execute that line. I guess I need to do more thorough testing before even thinking about delivery! Thanks Mark! Much appreciated,
Barton
Dec 18 '06 #10
Do you realize that you just saved me much embarrassment? This is due to be installed on a system that would certainly execute that line. I guess I need to do more thorough testing before even thinking about delivery! Thanks Mark! Much appreciated,
Barton
Hey, the debugger calls em like it sees em!
Dec 18 '06 #11
bartonc
6,596 Expert 4TB
Hey, the debugger calls em like it sees em!
I cleaned up the structure a bit while I was there:


Expand|Select|Wrap|Line Numbers
  1.     def InitFromConfig(self):
  2.         config = self.config
  3.         group = self.grpName
  4.  
  5.         if not config.Exists(group):
  6.             self.WriteRegistryGroup(group)
  7.  
  8.         else:
  9.             config.SetPath(group)
  10.             for var in self.GetVariables():
  11.                 name = var['name']
  12.                 if config.Exists(name):
  13.                     value = self.ReadRegistry(name, var['type'])
  14.                     self.SetVariables({name:value})
  15.                 else:
  16.                     self.WriteRegistry(name, var['value'], var['type'])
  17.         config.SetPath("")
  18.  
  19.     def WriteRegistryGroup(self, group):
  20.         self.config.SetPath(group)
  21.         for var in self.GetVariables():
  22.             self.WriteRegistry(var['name'], var['value'], var['type'])
  23.         self.config.SetPath("")
  24.  
Dec 18 '06 #12
bartonc
6,596 Expert 4TB
I cleaned up the structure a bit while I was there:


Expand|Select|Wrap|Line Numbers
  1.     def InitFromConfig(self):
  2.         config = self.config
  3.         group = self.grpName
  4.  
  5.         if not config.Exists(group):
  6.             self.WriteRegistryGroup(group)
  7.  
  8.         else:
  9.             config.SetPath(group)
  10.             for var in self.GetVariables():
  11.                 name = var['name']
  12.                 if config.Exists(name):
  13.                     value = self.ReadRegistry(name, var['type'])
  14.                     self.SetVariables({name:value})
  15.                 else:
  16.                     self.WriteRegistry(name, var['value'], var['type'])
  17.         config.SetPath("")
  18.  
  19.     def WriteRegistryGroup(self, group):
  20.         self.config.SetPath(group)
  21.         for var in self.GetVariables():
  22.             self.WriteRegistry(var['name'], var['value'], var['type'])
  23.         self.config.SetPath("")
  24.  
And here's how to initialize module-scope variables with either the values sent into the function or the registry values. Registry values are used if they exist.
Expand|Select|Wrap|Line Numbers
  1. import DefaultHolder as DH
  2. import wxdbtools as db
  3.  
  4. ## Don't actually have to declare these before making them global.
  5. dbDefaultHolder = None
  6. dbServer = None
  7. dbConnect = None
  8.  
  9. def InitDBDialog(HKey, group, user, password, host):
  10.     """Connect to database using registry defaults if they exist.
  11.        Return the connection or (which may be None)."""
  12.     global dbDefaultHolder, dbServer, dbConnect, dbServer, dbConnect
  13.     dbDefaultHolder = DH.DefaultValueHolder(HKey, group)
  14.     dbDefaultHolder.SetVariables(UserName=user, Password=password,
  15.                                  ServerName=host)  #, database='trails'
  16.     dbDefaultHolder.InitFromConfig()
  17.     dhVars = dbDefaultHolder.GetVariables()
  18.  
  19.     for var in dhVars:
  20.         execStr = "%s = %s" %(var['name'], (repr(var['value']), var['value'])[var['type'] != str])
  21.         exec(execStr) in globals()
  22.  
  23.     dbServer = db.DBServer(sys.stdout)
  24.     dbConnect = dbServer.Login(ServerName, UserName, Password)
  25.     return dbServer
Postponed dialog box instantiation is the reason for module-scope here. Once there are set up, my Login Dialog Box can be created on the fly, already connected to the database:
Expand|Select|Wrap|Line Numbers
  1. def create(parent):
  2.     return DBConnectDialog(parent, dbDefaultHolder, dbConnect, dbServer)
  3.  
  4. class DBConnectDialog(wx.Dialog):
  5.     def __init__(self, parent, defaultHolder, dbConnect, dbServer):
  6.         self._init_ctrls(parent)
  7.  
  8.         self.connectButton.SetDefault()
  9.         self.OkButton.Disable()
  10.  
  11.         self.defaultHolder = defaultHolder
  12.  
  13.         self.dbConnect = dbConnect  # save the connection so it can be closed
  14.         dbServer.SetMaster(self)
  15.         self.dbServer = dbServer
  16.  
  17.         self.SetWidgetData()
Dec 25 '06 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Paul C-T | last post by:
Hi, Am I trying to be too clever here? I am trying to write a PHP page to enable me to enter values into a form then write those values to a text file. I want to use the form & table that...
0
by: inquirydog | last post by:
Hi- I am using xml to hold configuration data for a project, and using schema to define what the configuration file should look like. I wanted to get some advice on an intelligant way to...
4
by: Patrick | last post by:
Hi I want tu use an app.config like the example below. The problem is, that i don't know how many Action-Tags there will be, because this can be changed by the user. When using...
1
by: Tumurbaatar S. | last post by:
Hi! In old ASP I used Application collection to store configuration settings like ADO connection string. In .NET, it seems, the preferred method is using Web.config file. Yes? If I'm right then...
10
by: Brett | last post by:
If I have many hard coded values such as file paths, file names, timeouts, etc, where is the best place to define them? Meaning, in the case something needs changing for example, rather than...
7
by: ProvoWallis | last post by:
I'm still learning python so this might be a crazy question but I thought I would ask anyway. Can anyone tell me if it is possible to join two dictionaries together to create a new dictionary using...
3
by: mwt | last post by:
I want to set default values for a ConfigParser. So far, its job is very small, so there is only one section heading, . Reading the docs, I see that in order to set default values in a...
4
by: RedHair | last post by:
I developed a Win form with VS.NET 2005 + .NET 2.0 in C# There are some application settings are "User" scope and stored in xxx.settings, I can access them via Settings class and changethem with...
6
by: Peted | last post by:
Hi, im wanting to store some custom text strings in the app.config file of a c# app, to be retreived and updated when the app runs. using c# 2005 express in my testing i am using the code...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.