user308827
user308827

Reputation: 22011

Checking if connection to database exists before opening a new one in python

import dataset

class db(object):
    _db_connection = None
    _db_cur = None

    def __init__(self):
        self._db_connection = dataset.connect(path_to_database)

    def __del__(self):
        self._db_connection.executable.close()

In the code above, I create a class to connect to an existing database on AWS. Is there a way I can check if connection is already open and if so, return existing connection rather than open a new connection?

Upvotes: 2

Views: 2231

Answers (4)

Artyer
Artyer

Reputation: 40891

You can use a descriptor for that:

class DBConn(object):
    conn = None

    def __get__(self, instance, owner):
        if instance is None:
            return self
        if self.conn is None or self.conn.closed():
            # Since this is a class attribute, it is shared by all instances
            self.conn = dataset.connect(path_to_database)
        return self.conn

    def __delete__(self, instance):
        self.conn.executable.close()
        self.conn = None

And then just use it as a property:

class DB(object):
    connection = DBConn()

db = DB()
db.connection.do_something()  # Opens a new connections
other_db = DB()
other_db.connection.do_something_else()  # Reuses same connection
del db.connection  # Closes the connection
other_db.connection.another_thing()  # Reopens the connection

Upvotes: 3

epinal
epinal

Reputation: 1465

It's called Singleton pattern take a look at: http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html

class OnlyOne(object):
    class __OnlyOne:
        def __init__(self):
            self.val = None
        def __str__(self):
            return `self` + self.val
    instance = None
    def __new__(cls): # __new__ always a classmethod
        if not OnlyOne.instance:
            OnlyOne.instance = OnlyOne.__OnlyOne()
        return OnlyOne.instance
    def __getattr__(self, name):
        return getattr(self.instance, name)
    def __setattr__(self, name):
        return setattr(self.instance, name)

Upvotes: 2

MrE
MrE

Reputation: 20808

on connect, you may get an exception if the driver can't connect

so you need to wrap your connect call into a

class db(object):
    _db_connection = None
    _db_cur = None

    def __init__(self):
       try:
           self._db_connection = dataset.connect(path_to_database)
       except WhateverExceptionYourDBDriverThrowsOnError:
           pass

    def __del__(self):
        if self._db_connection:
            self._db_connection.executable.close()

You didn't say what driver, what DB you use, so this is generic code. You need to replace the Exception type with the proper one thrown by your driver.

Upvotes: 1

PRMoureu
PRMoureu

Reputation: 13337

db.local.conn.closed # return True or False

I use it in this post

Upvotes: 1

Related Questions