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! - """Encapuslate a Default Values Object and Config File"""
-
-
from inspect import getmembers
-
import wx
-
-
class DefaultValueHolder(object):
-
"""Intended for use with wxConfig (or maybe _winreg) to set up and/or get
-
registry key names and values. Name attrs as default*. "default"
-
will be stripped of when reading and writing to the config file"""
-
## defaultTestStr = "this is a test"
-
## defaultTestInt = 1
-
-
def __init__(self, appName, grpName):
-
"""The name of the config file that will be created"""
-
self.appName = appName # if the key doesn't exit, it will be created
-
self.grpName = grpName # same goes for groups.
-
self.config = wx.Config(appName) # Open the file (HKCU in windows registry)
-
-
def GetVariables(self):
-
return [{"name":var[0][7:], "value":var[1], "type":type(var[1])}
-
for var in getmembers(self) if var[0].startswith('default')]
-
-
def SetVariables(self, **kwargs):
-
for name, value in kwargs.items():
-
setattr(self, "default" + name, value)
-
-
def InitFromConfig(self):
-
self.config.SetPath(self.grpName)
-
for var in self.GetVariables():
-
if var['type'] == str:
-
self.config.Write(var['name'], var['value'])
-
elif var['type'] == int:
-
self.config.WriteInt(var['name'], var['value'])
-
elif var['type'] == float:
-
self.config.WriteFloat(var['name'], var['value'])
-
-
-
if __name__ == "__main__":
-
test = DefaultValueHolder("MyAppName", "Database")
-
-
test.SetVariables(UserName = "joe", Password = "", ServerName = "MyServer")
-
#### this also works:
-
## test.defaultUserName = "joe"
-
-
test.InitFromConfig()
12 2618
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. - """Encapuslate a Default Values Object and Config File"""
-
-
from inspect import getmembers
-
import wx
-
-
class DefaultValueHolder(object):
-
"""Intended for use with wxConfig (or maybe _winreg) to set up and/or get
-
registry key names and values. Name attrs as default*. "default"
-
will be stripped of when reading and writing to the config file"""
-
-
def __init__(self, appName, grpName):
-
"""Open or create the application key"""
-
self.grpName = grpName # if the key or group doesn't exit, it will be created
-
self.config = wx.Config(appName) # Open the file (HKCU in windows registry)
-
-
def GetVariables(self):
-
return [{"name":var[0][7:], "value":var[1], "type":type(var[1])}
-
for var in getmembers(self) if var[0].startswith('default')]
-
-
def SetVariables(self, varDict={}, **kwargs):
-
kwargs.update(varDict)
-
for name, value in kwargs.items():
-
setattr(self, "default" + name, value)
-
-
def InitFromConfig(self):
-
config = self.config
-
group = self.grpName
-
-
if not config.Exists(group):
-
self.WriteRegistryGroup(Group)
-
return
-
-
config.SetPath(group)
-
for var in self.GetVariables():
-
name = var['name']
-
print name, "exists"
-
if config.Exists(name):
-
value = self.ReadRegistry(name, var['type'])
-
self.SetVariables({name:value})
-
else:
-
self.WriteRegistry(name, var['value'], var['type'])
-
config.SetPath("")
-
-
def UpdateConfig(self):
-
self.WriteRegistryGroup(self.grpName)
-
-
def WriteRegistryGroup(self, group):
-
self.config.SetPath(group)
-
for var in self.GetVariables():
-
self.WriteRegistry(var['name'], var['value'], var['type'])
-
self.config.SetPath("")
-
-
def ReadRegistry(self, name, type):
-
value = None
-
if type == str:
-
value = self.config.Read(name)
-
elif type in (int, long):
-
value = self.config.ReadInt(name)
-
elif type == float:
-
value = self.config.ReadFloat(name)
-
return value
-
-
def WriteRegistry(self, name, value, type):
-
print "writing registry", name, value, type
-
if type == str:
-
self.config.Write(name, value)
-
elif type in (int, long):
-
self.config.WriteInt(name, value)
-
elif type == float:
-
self.config.WriteFloat(name, value)
-
-
-
if __name__ == "__main__":
-
test = DefaultValueHolder("HETAP Pro 2.00", "Database")
-
test.SetVariables(UserName = "barton", Password = "", ServerName = "MyServer", database="trails")
-
test.InitFromConfig()
-
print test.GetVariables()
-
-
## #### this also works:
-
## ## test.defaultUserName = "joe"
-
##
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? - if not config.Exists(group):
-
self.WriteRegistryGroup(Group)
-
return
Thanks again Barton. Learning about new things is always interesting if not fun!
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? - if not config.Exists(group):
-
self.WriteRegistryGroup(Group)
-
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.
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? :)
You were just testing us, weren't you Barton? :)
THIS is the test: It didn't actually work! I Fixed it though... three lines: -
def SetVariables(self, varDict={}, **kwargs):
-
kwargs.update(varDict)
-
-
-
# in InitFromConfig...
-
self.SetVariables({name:value})
THIS is the test: It didn't actually work! I Fixed it though... three lines: -
def SetVariables(self, varDict={}, **kwargs):
-
kwargs.update(varDict)
-
-
-
# in InitFromConfig...
-
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.
Here it is in it's entirety. Sorry about the confussion. - """Encapuslate a Default Values Object and Config File"""
-
-
from inspect import getmembers
-
import wx
-
-
class DefaultValueHolder(object):
-
"""Intended for use with wxConfig (or maybe _winreg) to set up and/or get
-
registry key names and values. Name attrs as default*. "default"
-
will be stripped of when reading and writing to the config file.
-
You may not use the name varDict as one of the variable names."""
-
-
def __init__(self, appName, grpName):
-
"""Open or create the application key"""
-
self.appName = appName
-
self.grpName = grpName # if the key or group doesn't exit, it will be created
-
self.config = wx.Config(appName) # Open the file (HKCU in windows registry)
-
-
def GetVariables(self):
-
return [{"name":var[0][7:], "value":var[1], "type":type(var[1])}
-
for var in getmembers(self) if var[0].startswith('default')]
-
-
def SetVariables(self, varDict={}, **kwargs):
-
kwargs.update(varDict)
-
for name, value in kwargs.items():
-
setattr(self, ("default" + name), value)
-
-
def InitFromConfig(self):
-
config = self.config
-
group = self.grpName
-
-
if not config.Exists(group):
-
self.WriteRegistryGroup(group)
-
-
else:
-
config.SetPath(group)
-
for var in self.GetVariables():
-
name = var['name']
-
if config.Exists(name):
-
value = self.ReadRegistry(name, var['type'])
-
self.SetVariables({name:value})
-
else:
-
self.WriteRegistry(name, var['value'], var['type'])
-
config.SetPath("")
-
-
def WriteRegistryGroup(self, group):
-
self.config.SetPath(group)
-
for var in self.GetVariables():
-
self.WriteRegistry(var['name'], var['value'], var['type'])
-
self.config.SetPath("")
-
-
def UpdateConfig(self):
-
self.WriteRegistryGroup(self.grpName)
-
-
def ReadRegistry(self, name, type):
-
value = None
-
if type == str:
-
value = self.config.Read(name)
-
elif type in (int, long):
-
value = self.config.ReadInt(name)
-
elif type == float:
-
value = self.config.ReadFloat(name)
-
return value
-
-
def WriteRegistry(self, name, value, type):
-
if type == str:
-
self.config.Write(name, value)
-
elif type in (int, long):
-
self.config.WriteInt(name, value)
-
elif type == float:
-
self.config.WriteFloat(name, value)
-
-
-
if __name__ == "__main__":
-
test = DefaultValueHolder("HETAP Pro 2.00", "Database")
-
test.SetVariables(UserName = "peter", Password = "pan", ServerName = "MyServer", database="")
-
test.InitFromConfig()
-
for line in test.GetVariables():
-
print line
-
-
## #### this also works:
-
## ## test.defaultUserName = "joe"
-
##
-
Here it is in it's entirety. Sorry about the confussion. - """Encapuslate a Default Values Object and Config File"""
-
-
...
-
-
def InitFromConfig(self):
-
config = self.config
-
group = self.grpName
-
-
if not config.Exists(group):
-
self.WriteRegistryGroup(Group)
-
return
-
-
Well, almost: -
if not config.Exists(group):
-
self.WriteRegistryGroup(group) # <<=== lowercase
-
return
-
:)
Cheers,
- Mark
Well, almost: -
if not config.Exists(group):
-
self.WriteRegistryGroup(group) # <<=== lowercase
-
return
-
:)
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
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!
Hey, the debugger calls em like it sees em!
I cleaned up the structure a bit while I was there: -
def InitFromConfig(self):
-
config = self.config
-
group = self.grpName
-
-
if not config.Exists(group):
-
self.WriteRegistryGroup(group)
-
-
else:
-
config.SetPath(group)
-
for var in self.GetVariables():
-
name = var['name']
-
if config.Exists(name):
-
value = self.ReadRegistry(name, var['type'])
-
self.SetVariables({name:value})
-
else:
-
self.WriteRegistry(name, var['value'], var['type'])
-
config.SetPath("")
-
-
def WriteRegistryGroup(self, group):
-
self.config.SetPath(group)
-
for var in self.GetVariables():
-
self.WriteRegistry(var['name'], var['value'], var['type'])
-
self.config.SetPath("")
-
I cleaned up the structure a bit while I was there: -
def InitFromConfig(self):
-
config = self.config
-
group = self.grpName
-
-
if not config.Exists(group):
-
self.WriteRegistryGroup(group)
-
-
else:
-
config.SetPath(group)
-
for var in self.GetVariables():
-
name = var['name']
-
if config.Exists(name):
-
value = self.ReadRegistry(name, var['type'])
-
self.SetVariables({name:value})
-
else:
-
self.WriteRegistry(name, var['value'], var['type'])
-
config.SetPath("")
-
-
def WriteRegistryGroup(self, group):
-
self.config.SetPath(group)
-
for var in self.GetVariables():
-
self.WriteRegistry(var['name'], var['value'], var['type'])
-
self.config.SetPath("")
-
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. -
import DefaultHolder as DH
-
import wxdbtools as db
-
-
## Don't actually have to declare these before making them global.
-
dbDefaultHolder = None
-
dbServer = None
-
dbConnect = None
-
-
def InitDBDialog(HKey, group, user, password, host):
-
"""Connect to database using registry defaults if they exist.
-
Return the connection or (which may be None)."""
-
global dbDefaultHolder, dbServer, dbConnect, dbServer, dbConnect
-
dbDefaultHolder = DH.DefaultValueHolder(HKey, group)
-
dbDefaultHolder.SetVariables(UserName=user, Password=password,
-
ServerName=host) #, database='trails'
-
dbDefaultHolder.InitFromConfig()
-
dhVars = dbDefaultHolder.GetVariables()
-
-
for var in dhVars:
-
execStr = "%s = %s" %(var['name'], (repr(var['value']), var['value'])[var['type'] != str])
-
exec(execStr) in globals()
-
-
dbServer = db.DBServer(sys.stdout)
-
dbConnect = dbServer.Login(ServerName, UserName, Password)
-
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: -
def create(parent):
-
return DBConnectDialog(parent, dbDefaultHolder, dbConnect, dbServer)
-
-
class DBConnectDialog(wx.Dialog):
-
def __init__(self, parent, defaultHolder, dbConnect, dbServer):
-
self._init_ctrls(parent)
-
-
self.connectButton.SetDefault()
-
self.OkButton.Disable()
-
-
self.defaultHolder = defaultHolder
-
-
self.dbConnect = dbConnect # save the connection so it can be closed
-
dbServer.SetMaster(self)
-
self.dbServer = dbServer
-
-
self.SetWidgetData()
Sign in to post your reply or Sign up for a free account.
Similar topics
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
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...
|
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...
|
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)...
|
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...
|
by: Defcon1945 |
last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
|
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....
|
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
|
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...
| |