mercredi 4 septembre 2019

Share Database Connection across modules

I am trying to access a pyodbc connection from multiple places within my code.

Currently the user passes in the connection details via command line, and I process them using plac.annotation, problem is, I do not know how to share this object across all the project. What I have so far is:

A Singleton Class for storing the connection

class DatabaseInstance:
    """
    Singleton Class holding a Database Connection
    """

    class __DatabaseInstance:
        def __init__(self, server, database, schema, table, user, password):
            self.server = server
            self.database = database
            self.schema = schema
            self.table = table
            self.username = user
            self.passw = password

        def __str__(self):
            return "{} DB: {}@[{}].[{}].[{}] @ {}".format(
                repr(self),
                self.server,
                self.database,
                self.schema,
                self.table,
                self.username,
            )

        def get_connection(self):
            """
            TODO
            """
            if DatabaseInstance.connection:
                return DatabaseInstance.connection
            else:
                DatabaseInstance.connection = pyodbc.connect(
                    "DRIVER=SQL Server;SERVER="
                    + self.server
                    + ";PORT=1433;DATABASE="
                    + self.database
                    + ";UID="
                    + self.username
                    + ";PWD="
                    + self.passw
                )
                return DatabaseInstance.connection

    instance = None
    connection = None

    def __init__(self, server, database, schema, table, user, password):
        if not DatabaseInstance.instance:
            DatabaseInstance.instance = DatabaseInstance.__DatabaseInstance(
                server, database, schema, table, user, password
            )

    def __getattr__(self, name):
        return getattr(self.instance, name)

Now, In my main, I get the params, and create an instance for the database:

connection = DatabaseInstance(
    server=server,
    database=database,
    schema=schema,
    table=table,
    user=user,
    password=passw,
)

The application needs to access this object from different modules and submodules, but connection is withing the scope of a function.

Is there a better way to do it than just passing down this object from function to function up until it is used by the necessary functions?

Aucun commentaire:

Enregistrer un commentaire