ZODB address list question (source is listed)...
Robert
bobh at hslda.org
Thu Jul 12 09:38:30 EDT 2001
I am a newbie at both Python and ZODB so I thought I would modify the
ZODB demo that Mr. Pelletier did. It does the Listing, Adding and
Quiting fine. But when I add a duplicate it does not tell me that that
"name" is already in the database.
Any help would be appreciated!
Bob
## ---- CODE ----
# Created: R.L. Hicks, 2001-07-12
# Notes:
# Modified version of ZODB paper by Michel Pelletier
#--
#--
# TO DO:
# o delete
# o search
# o sorting
#--
# import libs needed to run
from ZODB import DB
from ZODB.FileStorage import FileStorage
from ZODB.PersistentMapping import PersistentMapping
from Persistence import Persistent
class Employee(Persistent):
""" an employee """
def __init__(self, name, phone):
self.name = name
self.phone = phone
# setup the database
storage = FileStorage("employees.fs")
db = DB(storage)
connection = db.open()
root = connection.root()
# get the employees mapping, creating an empty mapping
# if it is necessary
if not root.has_key("employees"):
root["employees"] = {}
employees = root["employees"]
def listEmployees():
if len(employees.values()) == 0:
print "The database is empty."
print
return
for employee in employees.values():
print "Info: %s - %s" % (employee.name, employee.phone)
print
def addEmployee(name, phone):
if employees.has_key(name):
## the below does not print when a duplicate is created
print "There is already an employee with this name."
return
else:
employees[name, phone] = Employee(name, phone)
root['employees'] = employees # reassign to change list
get_transaction().commit()
print "Employee %s added to database." % name
print
if __name__ == "__main__":
while 1:
choice = raw_input("Press 'L' to list, 'A' to add, or 'Q' to quit:")
choice = choice.lower()
if choice == "l":
listEmployees()
elif choice == "a":
name = raw_input("Employee name:")
phone = raw_input("Employee Phone:")
addEmployee(name, phone)
elif choice == "q":
break
# close the database
connection.close()
More information about the Python-list
mailing list