I can not delete key in dbm

2

I made a basic program to store some data and I am in trouble if the user chooses to delete some stored dictionary key. The function that deletes the data in my program is this:

def EraseData(name):
'''
Apaga uma chave do dicionário do banco de dados.
'''
db = dbm.open('data.db', 'c')
del db[name]
db.close()

When I search the entries in my database I see that NOTHING has been deleted. It just does not work.

This is the link for all my code in GIT : link

    
asked by anonymous 07.07.2015 / 20:43

2 answers

1

As I said, you need to further detail your error. The function you've created works perfectly, but there are some flaws in your program that keep it from working.

First, syntax errors, in the CheckRg function, endorse the if correctly.

Second, in the ShowList function, you are giving db is not iterable. So, iterate over the bank keys:

for key in db.keys():
    ...

Finally, the part that actually prevents the EraseData function from working is the removal of the FileAlreadyExists exception in the SearchData function. The exception is being raised before closing the connection to the database. This prevents the EraseData function from opening a new connection (generating a new exception) and permanently delete an entry.

Logo:

def SearchData(nome):
    db = dbm.open('data.db', 'c')
    if name in db:
        db.close()
        raise FileAlreadyExists

After this has been done, the function works perfectly. Otherwise, we need more details on running your program.

    
08.07.2015 / 07:06
1

I have tested here, and using direct in interactive mode it works del (although the documentation of this module is very weak and does not even mention del nor does it appear in dir of the dbm object). >

My hypothesis is this: you have this EraseData function and you open, modify, and close the bank - however, I believe that if the same bank is open while you do these actions, it may be that when close the other copy of the bank that is open the keys that exist there are that they are valid. Do you have the database open in a context variable that calls EraseData (or in any other thread / context?)

I do not believe this module will work fine by opening more than one connection at the same time to the same file - even if it was thought to work like this: my suggestion is to open that bank at the beginning of the program, and just close it output. (use a try...finally clause to ensure that the close function is called - and, or pass the instance of the database to all the functions that access it, or create a class where one of the attributes is the instance of the database - and promote all functions for methods of that class, or simply leave a global variable with the bank instance (not as bad in Python as in C or other languages because "global" variables are not really "global" - they are module variables effective only in the namespace of that module)

    
08.07.2015 / 05:18