2

I have a django application that connects to multiple databases (more than 400). Database credentials change often. I cannot use django database support because it needs static setup.

So I create dynamic database connection when loading the page that return a cursor.

I have the following questions:

  • Is this an appropriate way to release a cursor (using destructor __del_ )
  • If I use the close() method directly, am I safe with my destructor
  • I should do something similar for the connection object, or just closing cursor is enough?
  • Is there any proposed standard solution for this?

    class MyDatabaseManager(object):
        def __init__(self, database_name):
            self.cursor = None
            #for safety in case next command return an exception
            self.cursor = some_object.get_cursor(database_name)
    
        def close(self):
            self.cursor.close()
            self.cursor = None
    
        def __del__(self):
            if not (self.cursor is None):
                self.close()
    
        def execute_query(self, sql_query, parameter_list):
            return self.cursor.execute(sql_query, parameter_list)
    
nkout
  • 491
  • 4
  • 11

1 Answers1

0

General consensus seems to be to not use __del__. To recap from previous answers:

  1. It can't be assumed to ever be called or when.
  2. The del keyword doesn't lead to __del__ being invoked.
  3. It may lead to garbage collection not working properly (memory leaks).
  4. Use an explicit approach instead (call clean-up function manually) or weak references.

That should answer your questions 1, 2 and 4. As to the 3. question: If the database adapter you are using conforms to the python dbapi2 (the prevailing form for dbms adapters) then closing the cursor does not mean the connection should be closed. So even when all created cursors have been closed, the connection stays open and rightly so, I would say.

Community
  • 1
  • 1
XORcist
  • 4,288
  • 24
  • 32