Archived:Persistent Storage in PySymbian
Article Metadata
The class below implements a wrapper around a e32dbm file in PySymbian which can be used as persistent storage:
import e32dbm
class PersistentStorage:
def __init__(self,filename):
try:
# Try to open an existing file
self.data = e32dbm.open(filename,"wf")
except:
# Failed: Assume the file needs to be created
self.data = e32dbm.open(filename,"nf")
def SetValue(self,key,value):
if str(value) == value:
# if value is a string, it needs special treatment
self.config[key] = "u\"%s\"" % value
else:
# otherwise simply convert it to a string
self.config[key] = str(value)
def GetValue(self,key):
try:
return eval(self.config[key])
except:
# Assume item doesn't exist (yet), so return None
return None
def Close(self):
self.data.close()
How to use this code
The following code shows how to use this class to change a persistent setting:
import appuifw
import persistentstorage
def Main():
# Create the store
storage = PersistentStorage("e:\\config")
# Retrieve position
position = storage.GetValue("position")
# Set a default if it didn't exist
if position == None:
position = (51.47,5.48)
# Query new values, show current as default
latitude = appuifw.query(u"Latitude:","float",position[0])
longitude = appuifw.query(u"Longitude:","float",position[1])
# If new values were given, store them
if latitude != None and longitude != None:
storage.SetValue("position",(latitude,longitude))
storage.Close()
Main()
Caveats
The PersistentStorage.SetValue() method wraps a string between quotes to have eval() parse it properly. However, this doesn't work right if you use the backslash character in a string. Basically, you need to double every backslash character to have eval() parse it correctly. To extend the code to do this automatically is left as an exercise for the reader.

